Control Focus of Multiple FormControl Fields

Deadly 提交于 2019-12-25 08:59:04

问题


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}
                        />

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)
    }
}

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.

EDIT

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


回答1:


My working solution:

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}
                        />

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.




回答2:


Unless you've set a ref with the key textInput1 then this won't work. Another suggestion would be to move all of the inputs into a separate component and then you can use this.props.children to traverse all your inputs and grab the input at whatever position you want.

EDIT:

You can also use the autoFocus prop to determine if an input should be focused or not.



来源:https://stackoverflow.com/questions/46570762/control-focus-of-multiple-formcontrol-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!