反应引用未定义

React ref undefined

所以我在 React 中使用 ref 时遇到了一些麻烦。

我想做的就是使用 ref 打印元素的文本内容,如下所示:

export default class SomeClass extends Component {
  constructor(props) {
    super(props);
    this.intro = React.createRef();
    console.log(this.intro.textContent);
  }

  render() {
    return (
      <div ref={this.intro}>Hi</div>
    )
  }
}

但是,这总是打印 null 或 undefined 而不是我想要的 "Hi"。

这是因为您将其记录在构造函数中。 运行 componentDidMount 生命周期中的代码。

export default class SomeClass extends Component {
  constructor(props) {
    super(props);
    this.intro = React.createRef();

  }


componentDidMount(){
      console.log(this.intro.textContent);
    }

  render() {
    return (
      <div ref={this.intro}>Hi</div>
    )
  }
}

在实际呈现 Dom 之前,您正在控制台登录构造函数。 尝试在 onClick 处理程序中登录控制台。

export default class SomeClass extends Component {
 constructor(props) {
  super(props);
  this.intro = React.createRef();
 }
 print = () => {
   console.log(this.intro.textContent);
 }
 render() {
   return (
     <div>
       <div ref={this.intro}>Hi</div>
       <button onClick={this.print}>Print</div>
     </div>
   )
 }

}

您应该将 currentref 一起使用,例如 this.ref.current.textContent

查看 stackblitz 演示 Here

export default class App extends Component {
  constructor(props) {
    super(props);
    this.intro = React.createRef();
  }

 componentDidMount(){
      console.log( this.intro.current.textContent);
    }

 render() {
    return (
      <div ref={this.intro}>Hi</div>
    )
  }
}