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

Sha*_*oux 12 javascript ref reactjs

我试图做这个.

我必须遗漏一些东西,但我不明白为什么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>;
  }
}
Run Code Online (Sandbox Code Playgroud)

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

May*_*kla 19

因为您忘记将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>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

工作实例.

  • 我意识到不久前已经回答了这个问题,但您提供的工作示例显示“当前值:null”。难道不应该给出一个值吗? (3认同)

小智 13

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);
          });
      }
  }
Run Code Online (Sandbox Code Playgroud)

这是在这种情况下使用 React.createRef() 的正确方法。


Sai*_*uha 13

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


Nee*_*ani 9

在以下情况下可能会发生这种情况:

  • 您忘记将引用传递this.test给问题中的组件。

<Component ref={this.test} />

  • 您正在使用Redux,其中ref props 传递到的组件由方法包装connect,因此this.test.current会返回null,因为它指向 Redux 包装器,以使此类组件工作forwardRef: true

IE:connect(mapStateToProps, mapDispatchToProps, null, {forwardRef: true})(Component)

  • 如果您一起使用withRouterand ,那么您将有两个包装器connect,而不是一个,并且显然会返回null,为了克服这个问题,请确保包装 this.test.currentwithRouterconnect

withRouter(connect(mapStateToProps, mapDispatchToProps, null, {forwardRef: true})(Component))

进而

<Component wrappedComponentRef={ref => this.test = ref} />

wrappedComponentRef是一个用于使包装组件可用的道具,就像 一样forwardRef: true,您可以在此处的文档中找到它


AKX*_*AKX 5

您缺少ref={this.test}道具。

return (
  <div className="App" ref={this.test}>
    current value : {this.test.current + ""}
  </div>
);
Run Code Online (Sandbox Code Playgroud)