所以,从
https://facebook.github.io/react/docs/more-about-refs.html#the-ref-callback-attribute中提取
The ref attribute can be a callback function instead of a name. This callback will be executed immediately after the component is mounted. The referenced component will be passed in as a parameter,and the callback function may use the component immediately,or save the reference for future use (or both).
然后它仅给出了立即使用该组件的示例.我试图找出如何使用此功能立即访问组件,并保存组件以供将来使用,正如我们所说的那样.
要继续他们特定的focus()和输入示例,我将如何在input元素上调用focus(),并将其保存到refs中的theInput键?
或者换一种方式,我将如何使这个小提琴中的console.log返回一个带有输入元素组件的输入键的对象ref:https://jsfiddle.net/qo3p3fh1/1/
为了完整起见,我在这里包含了代码.
来自你小提琴的HTML:
<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>
更新反应脚本改变使用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'));