javascript - 引用未定义 react

标签 javascript reactjs

所以我遇到的问题是我试图每 5 秒打印一次 ref 的 textContent,这在第一次从 componentDidMount() 调用 typeWrite() 时有效,但是当它被递归调用时(使用setTimeout()) 时,我收到一条错误消息,指出 this.intro.current 未定义,即使它是在函数第一次运行时定义的。

我想保持结构相对相似(我不想改变太多),因为我遗漏了其他依赖于这个结构的东西。

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

  componentDidMount() {
    this.typeWrite();
  }

  typeWrite() {
    console.log(this.intro.current.textContent);
    setTimeout(this.typeWrite, 5000);
  }
  render() {
    return (
      <div className="intro" ref={this.intro}>Text</div>
    )
  }
}

最佳答案

您需要将函数绑定(bind)到组件。

  constructor(props) {
    super(props);
    this.intro = React.createRef();
    this.typeWrite = this.typeWrite.bind(this);
  }

或者您需要使用箭头函数调用您的函数。

  typeWrite() {
    console.log(this.intro.current.textContent);
    setTimeout(() => this.typeWrite(), 5000);
  }

关于javascript - 引用未定义 react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60345735/

相关文章:

javascript - $(document).scroll 仅在 IE8 中不会触发

javascript - 当在配置中设置规则数组时,Webpack 无法识别 JSX

javascript - 谷歌地图标记作为 Reactjs 组件

javascript - 语法 高阶组件 - Autosizer

javascript - 在 React 和 jQuery 中获取鼠标坐标

javascript - 在 React 中读取 CSV 文件

javascript - 使用 Angular 进行点赞 => 滑动功能

javascript - ESLint : TopBarClass not found in './TopBar' (import/named)

javascript - javascript 中没有任何值仍然为 true

javascript - 如何解构嵌套对象