首页 > 解决方案 > 在父组件的每个渲染上为输入设置自动对焦

问题描述

我有一个应用了样式的输入组件,称为 StyledInput,它位于 NumericInputComponent 中,该组件在 PriceComponent 中使用。这是一行的一部分。每当我在两行之间切换时,我都想专注于这个输入。自动对焦仅适用于第一次渲染,因此当我切换时,它不会再次自动对焦。我如何强制每次切换的焦点。

我尝试强制重新渲染价格组件,但这对焦点没有帮助。

在数字输入中


const StyledInput = styled('input')`
    transition: all 150ms;
    &:hover {
        border: 1px solid ${Colors.brands['04']};
    }    
`;


   <StyledInput
                type='tel'
                autoComplete='off'
                autoFocus={this.props.autoFocus}
                min={this.props.min}
                max={this.props.max}
                step={this.props.step}
                value={this.props.value}
                onFocus={this.props.onFocus}
                disabled={this.props.disabled}
                onClick={this.stopPropagation}
                required={this.props.required}
                onChange={this.handleInputChange}
                className={this.props.className}
                onBlur={this.props.onBlur}
                ref={input => input && input.focus()}
            />

PriceComponenet 内部

const StyledNumericInput = styled(NumericInput)`
    padding: 0;          // remove mi-form-control padding
    text-align: center;
    &:required:focus {
        background-image: none;
    }
`;

<StyledNumericInput
                    autoFocus={this.shouldAutoFocus(this.props)}
                    className='mi-class'
                    value={this.state.value}
                    onChange={this.handleInputChange}
                    min={this.props.line ? -99.9 : 0.0}
                    id={'priceEdit' + this.props.index}
                    max={99.9}
                    step={0.1}
                    onFocus={Utilities.selectAllText}
                    required
                />

Say I have 3 lines, everytime I swtich between lines (which will have name, qty and price), it should always focus on price, even when the name and qty does not change.

标签: reactjs

解决方案


推荐阅读