Javascript 反应无法读取未定义的属性“绑定”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46707216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
React Cannot read property 'bind' of undefined
提问by Kat
I am stuck with an issue that I don't understand with binding. I tried all ways of binding in all questions relative to this issue in StackOverflow but every time I have the same
我遇到了一个我不理解绑定的问题。我在 StackOverflow 中尝试了与此问题相关的所有问题的所有绑定方法,但每次我都有相同的
Error: "React Cannot read property 'bind' of undefined"
Error2:"TypeError: Cannot read property '__reactInternalInstance$b7iw1elmz95' of null at
Object.getClosestInstanceFromNode"
错误:“React 无法读取未定义的属性‘绑定’”
错误 2:“类型错误:无法读取 null 处的属性 '__reactInternalInstance$b7iw1elmz95'
Object.getClosestInstanceFromNode"
Because I've tried everything, I wonder if is that a real problem with the binding of an external problem.
因为我什么都试过了,我想知道这是否是外部问题绑定的真正问题。
What I want to do is when I click on a button, another content appear.
我想要做的是当我单击一个按钮时,会出现另一个内容。
Here is my code :
这是我的代码:
import React, {Component} from 'react';
export default class Projects extends Component {
constructor(){
super();
this.state = {
onShow: false,
opacity: 0,
height: 0
}
}
OnShow(){
this.setState({
onShow: !this.state.onShow,
opacity: this.state.opacity === 0 ? 1:0,
height: '100vh'
});
}
render(){
return(
<div>
<h2>blabla</h2><p>some extra blabla</p>
<button onClick={this.onShow.bind(this)}>
<div opacity={this.state.opacity}>YO</div>
</button>
</div>
);
}
}
回答by Andy Theos
There is a typo in onClick on button:
this.OnShow.bind(this)is the right way.
onClick on button 中有一个错字:
this.OnShow.bind(this)是正确的方法。
Function is named OnShow, the state var is named onShow
函数名为 OnShow,状态变量名为 onShow
回答by Chtiwi Malek
First, there's a typo in your function name call.
首先,您的函数名称调用中有一个拼写错误。
But also, instead of manually binding this, I would recommend letting JS do the binding automatically, by using an Arrow Functionsyntax :
而且,我建议使用箭头函数语法让 JS 自动进行绑定,而不是手动绑定this:
OnShow = () => {
// your code here
}
render(){
return(
<div>
<button onClick={this.OnShow}>
mybutton
</button>
</div>
);
}
It's more elegant and saves you time.
它更优雅,更节省您的时间。
回答by Vivek Doshi
It's a typo mistake :
这是一个错字错误:
Original function is :
原来的功能是:
OnShow(){ ... }
So , Please change :
所以,请改变:
From :
从 :
this.onShow.bind(this)
To :
到 :
this.OnShow.bind(this)

