控制多个 FormControl 字段的焦点 [英] Control Focus of Multiple FormControl Fields

查看:37
本文介绍了控制多个 FormControl 字段的焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a mapped list of input fields:

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

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

I am currently using onKeyPress to handle submit:

_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 文档 有一个示例 使用 ref={(input) => 手动将焦点设置在单个输入字段上{ this.textInput = 输入;}}/>.我曾尝试使用 this['textInput'+'1'].focus() (使用 计算属性名称,但收到函数无效的错误.

I am attempting to focus on the next input field after the current one is successfully submitted. React documentation has an example for manually setting focus on a single input field using ref={(input) => { this.textInput = input; }} />. I have tried using this[‘textInput’+‘1’].focus() (using computed property names, but am getting an error that function is invalid.

编辑

Per Chase 的回答,我正在链接到自动对焦文档,尽管它没有在这种情况下工作.

Per Chase's answer, I am linking to the autofocus documentation, although it doesn't work in this case.

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) 对于 Bootstrap 的 FormControl 组件,我应该使用 inputRef 而不是 ref见这里.2)我正在使用 ilya-semenov 非常简洁的代码.

What I corrected in my code: 1) I am supposed to use inputRef instead of ref for Bootstrap's FormControl component, see here. 2) I am using ilya-semenov's very neat code.

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

Update I have other buttons on the page, when user presses them and is at bottom of page, page jumps up to top. Not sure why.

这篇关于控制多个 FormControl 字段的焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆