使用 React.createRef 时 current 总是 null

新手上路,请多包涵

我正在尝试这样

我一定是遗漏了什么,但我不明白为什么 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>;
  }
}

你可以 在这里 查看我的测试用例

原文由 Sharcoux 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
2 个回答

因为您忘记将 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">
        <input ref={this.test} />
        <button onClick={this.handleClick}>Get Value</button>
      </div>
    )
  }
}

工作示例。

原文由 Mayank Shukla 发布,翻译遵循 CC BY-SA 4.0 许可协议

我知道这不是 OP 问题的解决方案,但对于那些来自谷歌搜索的人来说,ref.current 可以为 null 的一种方式是,如果附加 ref 的组件是连接的组件。就像 react-redux connect 或 withRouter 一样。对于 react-redux,解决方案是在第四个选项中传递 forwardRef:true 以进行连接。

原文由 sktguha 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题