reactjs - 使用 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>
);
}
}
解决方案
要访问 ref 的值,您需要使用ref.current
. 在你的情况下,那将是this.tl.current
. 阅读文档以获取更多信息。
推荐阅读
- winapi - SspiPromptForCredentials 目标名称
- javascript - Three.js 360 图像 - 纹理标记为更新,但图像不完整
- javascript - 阿拉伯语脚本在 Google 的开发者工具模拟器上呈现不正确
- android - 有没有办法为按钮创建 android:text 状态选择器?
- java - cucumber.runtime.CucumberException:初始化浏览器时添加cookie时无法实例化类stepDefinitions
- python - 如何重新启动女服务员?
- php - 使内爆语句按我需要的方式工作
- node.js - 如何在 Node.js 中将 NTLM 凭据转换为 Kerberos 令牌
- c# - 为什么我的异步命令调用单元测试不起作用?
- java - 如何在不同的位置设置 JDropDown 子菜单