在组件渲染后,react如何设置聚焦在特定文本字段上?
文档似乎建议使用参考,例如:
在渲染函数的输入字段上设置ref="nameInput",然后调用:
this.refs.nameInput.getInputDOMNode().focus();
但是我该把它叫什么呢?我在几个地方试过了,但都不行。
在组件渲染后,react如何设置聚焦在特定文本字段上?
文档似乎建议使用参考,例如:
在渲染函数的输入字段上设置ref="nameInput",然后调用:
this.refs.nameInput.getInputDOMNode().focus();
但是我该把它叫什么呢?我在几个地方试过了,但都不行。
当前回答
React文档现在有一个专门的部分。https://facebook.github.io/react/docs/more-about-refs.html#the-ref-callback-attribute
render: function() {
return (
<TextInput
ref={function(input) {
if (input != null) {
input.focus();
}
}} />
);
},
其他回答
这不再是最好的答案。从v0.13开始,这个。在某些奇怪的情况下,refs可能在AFTER componentDidMount()运行之前不可用。
只需将autoFocus标签添加到输入字段,如上面的FakeRainBrigand所示。
ReactDOMComponent:不要访问DOM节点的.getDOMNode();相反,直接使用节点。这个DOM节点由App渲染。
应该是
componentDidMount: function () {
this.refs.nameInput.focus();
}
引用:@Dave对@Dhiraj的回答的评论;另一种方法是在被呈现的元素上使用ref属性的回调功能(在组件第一次呈现之后):
<input ref={ function(component){ React.findDOMNode(component).focus();} } />
更多信息
自动对焦对我来说效果最好。我需要将一些文本更改为双击文本的输入,所以这是我最终得到的:
<input autoFocus onFocus={this.setCaretToEnd} value={this.state.editTodo.value} onDoubleClick={this.updateTodoItem} />
注意:要修复React在文本开头放置插入符号的问题,请使用以下方法:
setCaretToEnd(event) {
var originalText = event.target.value;
event.target.value = '';
event.target.value = originalText;
}
在这里找到: https://coderwall.com/p/0iz_zq/how-to-put-focus-at-the-end-of-an-input-with-react-js
最简单的答案是在输入文本元素中添加ref="some name"并调用下面的函数。
componentDidMount(){
this.refs.field_name.focus();
}
// here field_name is ref name.
<input type="text" ref="field_name" />