为什么我在构造函数中的绑定不起作用?
Why is my binding in constructor not working?
在我的 React 本机应用程序中,我有一个函数,用于当用户按下一个使用 setState 的按钮 (handleButtonAPressed) 时,所以我试图在我的构造函数中使用以下代码绑定它
const handleButtonAPressed = () => {
this.setState({x: this.state.x + 1});
}
export default class SvgExample extends React.Component {
constructor(props) {
super(props);
this.state = { x: 0, y: 0 };
this.handleButtonAPressed = this.handleButtonAPressed.bind(this);
}
render() {
return (
<View>
<RoundButton onPress={handleButtonAPressed} />
</View>
);
}
}
但是,我收到错误消息:
'TypeError: undefined is not an object (evaluating '_this2.handleButtonAPressed.bind)
handleButtonAPressed
应该在您的 class 内,这样您就可以 this.handleButtonAPressed.bind(this)
。如果你没有 handleButtonAPressed
内在你 class,this.handleButtonAPressed
将是 undefined
并且不可能做到 .bind
.
这是你应该做的
export default class SvgExample extends React.Component {
constructor(props) {
super(props);
this.state = { x: 0, y: 0 };
this.handleButtonAPressed = this.handleButtonAPressed.bind(this);
}
handleButtonAPressed() {
this.setState({x: this.state.x + 1});
}
render() {
return (
<View>
<RoundButton onPress={handleButtonAPressed} />
</View>
);
}
}
在我的 React 本机应用程序中,我有一个函数,用于当用户按下一个使用 setState 的按钮 (handleButtonAPressed) 时,所以我试图在我的构造函数中使用以下代码绑定它
const handleButtonAPressed = () => {
this.setState({x: this.state.x + 1});
}
export default class SvgExample extends React.Component {
constructor(props) {
super(props);
this.state = { x: 0, y: 0 };
this.handleButtonAPressed = this.handleButtonAPressed.bind(this);
}
render() {
return (
<View>
<RoundButton onPress={handleButtonAPressed} />
</View>
);
}
}
但是,我收到错误消息:
'TypeError: undefined is not an object (evaluating '_this2.handleButtonAPressed.bind)
handleButtonAPressed
应该在您的 class 内,这样您就可以 this.handleButtonAPressed.bind(this)
。如果你没有 handleButtonAPressed
内在你 class,this.handleButtonAPressed
将是 undefined
并且不可能做到 .bind
.
这是你应该做的
export default class SvgExample extends React.Component {
constructor(props) {
super(props);
this.state = { x: 0, y: 0 };
this.handleButtonAPressed = this.handleButtonAPressed.bind(this);
}
handleButtonAPressed() {
this.setState({x: this.state.x + 1});
}
render() {
return (
<View>
<RoundButton onPress={handleButtonAPressed} />
</View>
);
}
}