【问题标题】:Control Focus of Multiple FormControl Fields多个 FormControl 字段的控制焦点
【发布时间】:2018-03-16 04:41:34
【问题描述】:

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

                      <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 文档 has an example 用于使用 ref={(input) =&gt; { this.textInput = input; }} /&gt; 手动将焦点设置在单个输入字段上。我尝试过使用this[‘textInput’+‘1’].focus()(使用computed property names,但我收到一个错误,即函数无效。

编辑

根据 Chase 的回答,我链接到自动对焦文档 although it doesn't work in this case。

https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/autofocus

【问题讨论】:

  • 我的答案不再起作用了吗?看起来它已作为答案被删除。
  • 部分不行,看我的评论。但我重新接受了替代答案。

标签: reactjs react-bootstrap


【解决方案1】:

我的工作解决方案:

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 组件see here。 2) 我正在使用 ilya-semenov 非常简洁的code。

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

【讨论】:

  • 嗯,好吧,所以你正在破解 ref 道具。很脏,但它工作大声笑
【解决方案2】:

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

编辑:

您还可以使用 autoFocus 属性来确定输入是否应该被聚焦。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2018-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多