[英]React setState between components ES6
I have a very simple application where I am trying to update the state of a parent component from a child component as follows: 我有一个非常简单的应用程序,我试图从子组件更新父组件的状态,如下所示:
import React from '../../../../../../../dependencies/node_modules/react';
import ReactDOM from '../../../../../../../dependencies/node_modules/react-dom';
class CalendarMain extends React.Component {
constructor() {
super();
}
handleClick() {
this.props.handleStateClick("State Changed");
}
render() {
return (
<div>
<div className="calendar">
{this.props.checkIn}
<button onClick={ this.handleClick.bind(this) }>Click Me</button>
</div>
</div>
)
}
}
class CalendarApp extends React.Component {
constructor() {
super();
this.state = {
checkIn: "Check-in",
checkOut: "Check-out",
dateSelected: false
};
}
handleStateClick( newState ) {
this.setState({
checkIn: newState
});
}
render() {
return (
<div>
<CalendarMain
checkIn = { this.state.checkIn }
handleStateClick = { this.handleStateClick.bind(this) }
/>
</div>
);
}
}
The error I am receiving is this.setState is not a function
and I can't work out why. 我收到的错误是
this.setState is not a function
,我this.setState is not a function
原因。 Any help would be much appreciated! 任何帮助将非常感激!
this
is not auto-bound in ES6 style syntax. this
不是ES6样式语法中的自动绑定。
Either: 或者:
this.func = this.func.bind(this)
this.func = this.func.bind(this)
func = () => {};
func = () => {};
More here: https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding 更多信息: https : //facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding
Use () =>
lambda to provide lexical scoping and bind correct value of this within the method handleStateClick()
: 使用
() =>
lambda提供词法作用域并在方法handleStateClick()
绑定this的正确值:
handleStateClick = () => {
this.setState({
checkIn: newState
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.