首页 > 解决方案 > 使用 Refs 访问子状态 - 无法读取未定义的属性“值”

问题描述

新手反应:

错误 无法读取未定义的属性“值”

这发生在我单击其中一个单元组件之后。我想将 this.tl.state.value 打印到控制台。

父组件

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

  checkForWinner = () => {
    console.log("Checking for winner..." + this.tl.state.value);
  }
  
  render() {
    return (
      <div className="App">
        <Cell ref={this.tl} winnercheck={this.checkForWinner} />
      </div>
    );
  }
}

子组件

class Cell extends Component {
    constructor(props) {
        super(props);
        this.state = {
            value: "X"
        }
    }

    toggleVal = () => {

        this.props.winnercheck();
    }
    
    render() {
        return (
            <div onClick={() => this.toggleVal()}>
                {this.state.value}
            </div>
        );
    }
}

标签: reactjs

解决方案


要访问 ref 的值,您需要使用ref.current. 在你的情况下,那将是this.tl.current. 阅读文档以获取更多信息。


推荐阅读