那么,从https://facebook.github.io/react/docs/more-about-refs.html#the-ref-callback-attribute中提取
ref属性可以是回调函数而不是名称。此回调将在组件挂载后立即执行。被引用的组件将作为参数传入,回调函数可以立即使用该组件,或者保存引用以备将来使用(或两者兼用)。
然后它只给出了一个立即使用该组件的示例。我正试图找出如何使用此函数立即访问组件,和保存组件以供将来使用,因为它说我们能够做到。
继续他们特定的focus()
和theInput
的例子,我如何在输入元素上调用focus()
,并将其保存到refs中的theInput
键?
或者换句话说,我如何使console.log
在这个fiddle返回一个对象的theInput
键的输入元素的组件ref: https://jsfiddle.net/qo3p3fh1/1/
我真的不理解选择的答案,小提琴只是返回一个空对象。
进一步阅读ES6的用法,你会发现:
render: function() {
return <TextInput ref={(c) => this._input = c} />;
},
componentDidMount: function() {
this._input.focus();
},
所以你需要做的是将该组件分配给一个var
,你可以挂在上面,可能是this
的例子,然后你可以使用this._input
来控制你的组件。
为了完整,我在这里包含了代码。
HTML from your fiddle:
<script src="https://facebook.github.io/react/js/jsfiddle-integration.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
更新了react脚本,改变了refs的使用方式,点击这里(https://jsfiddle.net/mark1z/q9yg70ak/)
var Hello = React.createClass({
componentDidMount: function(){
React.findDOMNode(this.refs['theInput']).focus();
},
render: function() {
return (
<div>
<input type="text" ref='theInput'/>
<input type="button" onClick={ this.submitForm } value="Submit!" />
</div>
);
},
submitForm: function() {
console.log( this.refs['theInput'] );
}
});
React.render(<Hello />, document.getElementById('container'));
我不确定这是一个好方法,但它的工作。试试吧!https://jsfiddle.net/qo3p3fh1/2/
<input type="text" ref={ function(component) { React.findDOMNode( component ).focus(); self.refs = {'theInput': component } } } />
ES6版本
export default class Hello extends React.Component {
componentDidMount() {
// let textarea get focus when page loaded
this.textArea.focus();
}
sendMessage(e) {
console.log(this.textArea);
}
render() {
return (
<textarea
placeholder="say something..." ref={(ref) => {
this.textArea = ref;
}} onKeyPress={(e) => this.sendMessage(e)} autoComplete="off"
>
</textarea>
);
}
};
下面的代码可以为您工作吗?
var Hello = React.createClass({
componentDidMount: function(){
this.node.focus()
},
render: function() {
return (
<div>
<input type="text" ref={node => this.node = node} />
<input type="button" onClick={ this.submitForm } value="Submit!" />
</div>
);
},
submitForm: function() {
console.log(this.node);
}
});
React.render(<Hello />, document.getElementById('container'));
很好的阅读,为什么不使用findDOMNode()