Javascript 使用 React.createRef 时 current 始终为 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/51693111/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
current is always null when using React.createRef
提问by Sharcoux
I was trying to do this.
我试图做这个。
I must be missing something, but I don't understand why currentis always nullin this example.
我一定遗漏了一些东西,但我不明白为什么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>;
  }
}
You can check my test case here
你可以在这里查看我的测试用例
回答by Mayank Shukla
Because you forgot to assign the ref to some dom element. You are only creating it.
因为您忘记将 ref 分配给某个 dom 元素。你只是在创造它。
Write it like this:
像这样写:
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>
    )
  }
}
回答by Rex Raphael
React.createRef() is asynchronous so if you try to access the ref in componentDidMount, it will return null and later return the properties of the component in which you are referencing.
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);
          });
      }
  }
This is the right way to use the React.createRef() in this context.
这是在这种情况下使用 React.createRef() 的正确方法。
回答by AKX
You're missing the ref={this.test}prop.
你缺少ref={this.test}道具。
return (
  <div className="App" ref={this.test}>
    current value : {this.test.current + ""}
  </div>
);

