多个FormControl字段的控制焦点



我有一个映射的输入字段列表:

                      <FormControl
                            name={row_index}
                            value={barcode.barcode}
                            placeholder="Barcode - then Enter"
                            onChange={this.onChange}
                            onKeyPress={this._handleKeyPress}
                            disabled={barcode.submitted}
                        />

我目前正在使用onKeyPress来处理提交:

_handleKeyPress = (e) => {
    if (e.key === 'Enter') {
        const name = e.target.name;
        const barcodes = this.state.barcodes;
        const this_barcode = barcodes[name];
        let apiFormatted = {"barcode": this_barcode.barcode, "uid": this.props.currentSession}
        this.postBarcodeAPI(apiFormatted, name)
    }
}

我正在尝试关注成功提交当前输入字段。React Docudmentation具有一个示例,用于使用ref={(input) => { this.textInput = input; }} />手动将重点放在单个输入字段上。我尝试使用this[‘textInput’+‘1’].focus()(使用计算属性名称,但是正在遇到一个错误,该功能无效。

编辑

根据Chase的答案,我正在链接到自动对焦文档,尽管在这种情况下它不起作用。

https://developer.mozilla.org/en-us/docs/web/api/htmlselectelement/autofocus

我的工作解决方案:

const focusing = index === lastSubmittedIndex + 1 ? true : false;
const refText = focusing || index === 0 ? input => input && input.focus() : null;
                        <FormControl
                            name={row_index}
                            value={barcode.barcode}
                            placeholder="Barcode - then Enter"
                            onChange={this.onChange}
                            onKeyPress={this._handleKeyPress}
                            disabled={barcode.submitted || barcode.apiCalling}
                            inputRef={refText}
                        />

我在代码中纠正的内容: 1)我应该将inputRef而不是ref用于Bootstrap的FormControl组件,请参见此处。 2)我正在使用Ilya-Semenov的非常整洁的代码。

更新我在页面上还有其他按钮,当用户按下它们并且在页面底部时,页面跳到顶部。不知道为什么。

,除非您使用键textInput1设置了ref,否则这将行不通。另一个建议是将所有输入移动到一个单独的组件中,然后您可以使用this.props.children遍历所有输入,并在您想要的任何位置上获取输入。

编辑:

您也可以使用autoFocus Prop来确定输入是否应集中在。

最新更新