在组件渲染后,react如何设置聚焦在特定文本字段上?
文档似乎建议使用参考,例如:
在渲染函数的输入字段上设置ref="nameInput",然后调用:
this.refs.nameInput.getInputDOMNode().focus();
但是我该把它叫什么呢?我在几个地方试过了,但都不行。
在组件渲染后,react如何设置聚焦在特定文本字段上?
文档似乎建议使用参考,例如:
在渲染函数的输入字段上设置ref="nameInput",然后调用:
this.refs.nameInput.getInputDOMNode().focus();
但是我该把它叫什么呢?我在几个地方试过了,但都不行。
当前回答
由于这个错误有很多原因,我想我也会发布我所面临的问题。对我来说,问题是我将我的输入呈现为另一个组件的内容。
export default ({ Content }) => {
return (
<div className="container-fluid main_container">
<div className="row">
<div className="col-sm-12 h-100">
<Content /> // I rendered my inputs here
</div>
</div>
</div>
);
}
这是我调用上述组件的方式:
<Component Content={() => {
return (
<input type="text"/>
);
}} />
其他回答
@Dhiraj的答案是正确的,为了方便,你可以使用自动对焦道具在安装时自动对焦:
<input autoFocus name=...
注意,在jsx中,它是自动聚焦(大写F),不像普通的旧html是不区分大小写的。
要将焦点移动到新创建的元素上,您可以将元素的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(即当我更新其他状态时,它不会一直窃取焦点)。
根据更新后的语法,你可以使用this.myRref.current.focus()
你应该在componentDidMount和refs回调中做。就像这样
componentDidMount(){
this.nameInput.focus();
}
class App extends React.Component{ componentDidMount(){ this.nameInput.focus(); } render() { return( <div> <input defaultValue="Won't focus" /> <input ref={(input) => { this.nameInput = input; }} defaultValue="will focus" /> </div> ); } } ReactDOM.render(<App />, document.getElementById('app')); <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.js"></script> <div id="app"></div>
从React 0.15开始,最简洁的方法是:
<input ref={input => input && input.focus()}/>