在组件渲染后,react如何设置聚焦在特定文本字段上?

文档似乎建议使用参考,例如:

在渲染函数的输入字段上设置ref="nameInput",然后调用:

this.refs.nameInput.getInputDOMNode().focus(); 

但是我该把它叫什么呢?我在几个地方试过了,但都不行。


当前回答

这一点对我很有用:

<input autoFocus={true} />

其他回答

您可以将该方法调用放在呈现函数中。或者在生命周期方法中,componentDidUpdate

最简单的答案是在输入文本元素中添加ref="some name"并调用下面的函数。

componentDidMount(){
   this.refs.field_name.focus();
}
// here field_name is ref name.

<input type="text" ref="field_name" />

根据更新后的语法,你可以使用this.myRref.current.focus()

要将焦点移动到新创建的元素上,您可以将元素的ID存储在状态中,并使用它来设置自动聚焦。如。

export default class DefaultRolesPage extends React.Component {

    addRole = ev => {
        ev.preventDefault();
        const roleKey = this.roleKey++;
        this::updateState({
            focus: {$set: roleKey},
            formData: {
                roles: {
                    $push: [{
                        id: null,
                        name: '',
                        permissions: new Set(),
                        key: roleKey,
                    }]
                }
            }
        })
    }

    render() {
        const {formData} = this.state;

        return (
            <GridForm onSubmit={this.submit}>
                {formData.roles.map((role, idx) => (
                    <GridSection key={role.key}>
                        <GridRow>
                            <GridCol>
                                <label>Role</label>
                                <TextBox value={role.name} onChange={this.roleName(idx)} autoFocus={role.key === this.state.focus}/>
                            </GridCol>
                        </GridRow>
                    </GridSection>
                ))}
            </GridForm>
        )
    }
}

通过这种方式,没有任何文本框获得页面加载的焦点(就像我想要的那样),但是当你按下“添加”按钮来创建一个新记录时,那么这个新记录就会获得焦点。

由于autoFocus不会再次“运行”,除非组件重新挂载,所以我不必费心取消this.state.focus(即当我更新其他状态时,它不会一直窃取焦点)。

从React 0.15开始,最简洁的方法是:

<input ref={input => input && input.focus()}/>