React - 在ref回调中保存组件

ste*_*tef 8 reactjs

因此,摘自https://facebook.github.io/react/docs/more-about-refs.html#the-ref-callback-attribute

ref属性可以是回调函数而不是名称.安装组件后将立即执行此回调.引用的组件将作为参数传入,并且回调函数可以立即使用该组件,或保存引用以供将来使用(或两者).

然后它仅给出了立即使用该组件的示例.我试图找出如何使用此功能立即访问组件,保存组件以供将来使用,正如我们所说的那样.

要继续他们的具体focus()theInput示例,我将如何调用focus()input元素,并将其保存到theInputrefs中的键?

或换句话说,我将如何使console.log这个小提琴返回一个带有theInput输入元素组件的键的对象ref:https://jsfiddle.net/qo3p3fh1/1/

Kha*_*tor 7

我并不真正理解所选择的答案,而小提琴只会返回一个空对象.

在ES6用法中进一步阅读本文档,您会发现:

render: function() {
  return <TextInput ref={(c) => this._input = c} />;
},
componentDidMount: function() {
  this._input.focus();
},
Run Code Online (Sandbox Code Playgroud)

因此,您需要做的是将该组件分配给var您可以挂起的组件,可能this在示例中更喜欢,稍后您可以使用它this._input来控制组件.


Mar*_*ark 4

为了完整性,我在此处包含了代码。

来自你的小提琴的 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>
Run Code Online (Sandbox Code Playgroud)

更新了反应脚本,改变了引用的使用方式,在这里进行修改(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'));
Run Code Online (Sandbox Code Playgroud)