reactjs - 获取类组件中事件的反应参考值的正确方法是什么?
问题描述
在类 Component 中获取事件的 react ref 值的权利是什么?
class ReactRef extends Component {
constructor(props) {
super(props);
this.buttonValue = React.createRef();
}
hasText() {
console.log(this.buttonValue.current); //Cannot read property 'buttonValue' of undefined
}
render(){
return(
<div>
<button type="text" ref={this.buttonValue} onClick={this.hasText}> Click me </button>
</div>
)
}
}
解决方案
您需要绑定hasText
到正确的范围。
您可以使用箭头函数声明它 -
hasText = () => {
// now you have access to this.buttonValue.current
}
或者你可以在你的构造函数中绑定它 -
constructor(props) {
super(props);
this.buttonValue = React.createRef();
this.hasText = this.hasText.bind(this);
}
推荐阅读
- django - 如何自动更新 ForeignKeys 以具有“, on_delete=models.PROTECT”
- mysql - SQL 替换语句的正确 MariaDB 语法
- python - SQLAlchemy - Session.merge() 返回重复的密钥完整性错误
- java - 如何获取 Google Play 订阅付款
- html - 如何仅使用 CSS 从 iFrame 中将图标粘贴到屏幕底部?
- c++ - C++ Aws S3 IOStream 在传递时被破坏。有没有办法防止这种情况发生?
- google-sheets - Google表格查询中一列中的ROUNDUP SUM值
- python - Django:有没有办法取消接收器触发特定模型信号?
- awk - awk 中的格式用完了
- angular - 从下拉列表中删除白色