【问题标题】:Is the correct way to access ref in react?在反应中访问 ref 的正确方法是什么?
【发布时间】:2016-10-08 22:37:43
【问题描述】:

如果不使用 this.say 到 this on 按钮的绑定,该示例将不起作用。但是我不确定它是否正确或有任何副作用。

class Speak extends React.Component {

    render() {
        return (
            <div>
                <input ref={(c) => this._input = c} defaultValue="Hello World!"/>
                <button onClick={this.say.bind(this) }>Say</button>
            </div>
        );
    }

    say() {
        if (this._input !== null) {
            alert(this._input.value);
        }
    }
};

ReactDOM.render(<Speak />, document.getElementById('App'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="App" />

【问题讨论】:

    标签: reactjs ref


    【解决方案1】:

    使用 ES6 类时似乎需要这样:See: Autobinding

    唯一的区别是上面的例子绑定了构造函数中的方法

    【讨论】:

      【解决方案2】:

      您可以利用数组函数而忘记添加.bind(this)
      查看工作pen

      class Speak extends React.Component {
          render() {
              return (
                  <div>
                      <input type='text' ref='greeting'/>
                      <button onClick={this.say}>Say</button>
                  </div>
              );
          }
      
          say = () => {
              const { value } = this.refs.greeting;
              alert(value);
              return value;
          };
      };
      
      ReactDOM.render(<Speak />, document.getElementById('App'));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多