代码之家  ›  专栏  ›  技术社区  ›  Sharcoux

使用React.createRef时,current始终为空

  •  4
  • Sharcoux  · 技术社区  · 7 年前

    我正试着去做 this .

    我一定漏掉了什么,但我不明白为什么 current 总是 null 在这个例子中。

    class App extends React.PureComponent {
      constructor(props) {
        super(props);
        this.test = React.createRef();
      }
      render() {
        return <div className="App">current value : {this.test.current + ""}</div>;
      }
    }
    

    你可以检查我的测试用例 here

    3 回复  |  直到 7 年前
        1
  •  20
  •   Mayank Shukla    7 年前

    因为您忘记将ref分配给某个dom元素。你只是在创造它。

    这样写:

    class App extends React.PureComponent {
      constructor(props) {
        super(props);
        this.test = React.createRef();
      }
    
      handleClick = () => alert(this.test.current.value)
    
      render() {
        return (
          <div className="App">
            current value : {(this.test.current || {}).value}
            <input ref={this.test} />
            <button onClick={this.handleClick}>Get Value</button>
          </div>
        )
      }
    }
    

    Working Example.

        2
  •  5
  •   AKX Bryan Oakley    7 年前

    你错过了 ref={this.test} 道具。

    return (
      <div className="App" ref={this.test}>
        current value : {this.test.current + ""}
      </div>
    );
    
        3
  •  4
  •   Rex Raphael    6 年前

    React.createRef()是异步的,因此如果您试图访问componentDidMount中的ref,它将返回null,然后返回您正在引用的组件的属性。

    componentDidMount(): void {
          if (this.viewShot && this.viewShot.current) {
              this.viewShot.current.capture().then((uri) => {
            console.log('do something with ', uri);
              });
          }
      }
    

    这是在此上下文中使用React.createRef()的正确方法。

    推荐文章