Reactjs,这是未定义的
Reactjs and this is undefined
我实际上正在尝试使用存储和操作开发一个简单的应用程序,并使用 fluxible 响应组件,但我遇到了一个问题。
其实在我的组件方法add()中,"this"是undefined...
不知道是什么问题...
这是我的组件:
从 'react' 导入 React;
class Client extends React.Component {
constructor (props) {
super(props);
}
add(e){
this.context.dispatch('ADD_ITEM', {name:'Marvin'});
}
render() {
return (
<div>
<h2>Client</h2>
<p>List of all the clients</p>
<button onClick={this.add}>Click Me</button>
<ul>
</ul>
</div>
);
}
}
Client.contextTypes = {
dispatch: React.PropTypes.func.isRequired
};
export default Client;
试试这个按钮:
<button onClick={this.add.bind(this)}>Click Me</button>
来自docs:
Methods follow the same semantics as regular ES6 classes, meaning that they don't automatically bind this to the instance. You'll have to explicitly use .bind(this) or arrow functions =>.
所以要么绑定函数(我觉得这很乏味):
<button onClick={this.add.bind(this)}>Click Me</button>
或者您可以启用并利用 Babel React ES6+ arrow functions feature:
add = (e) => {
this.context.dispatch('ADD_ITEM', {name:'Marvin'});
}
我实际上正在尝试使用存储和操作开发一个简单的应用程序,并使用 fluxible 响应组件,但我遇到了一个问题。
其实在我的组件方法add()中,"this"是undefined...
不知道是什么问题...
这是我的组件:
从 'react' 导入 React;
class Client extends React.Component {
constructor (props) {
super(props);
}
add(e){
this.context.dispatch('ADD_ITEM', {name:'Marvin'});
}
render() {
return (
<div>
<h2>Client</h2>
<p>List of all the clients</p>
<button onClick={this.add}>Click Me</button>
<ul>
</ul>
</div>
);
}
}
Client.contextTypes = {
dispatch: React.PropTypes.func.isRequired
};
export default Client;
试试这个按钮:
<button onClick={this.add.bind(this)}>Click Me</button>
来自docs:
Methods follow the same semantics as regular ES6 classes, meaning that they don't automatically bind this to the instance. You'll have to explicitly use .bind(this) or arrow functions =>.
所以要么绑定函数(我觉得这很乏味):
<button onClick={this.add.bind(this)}>Click Me</button>
或者您可以启用并利用 Babel React ES6+ arrow functions feature:
add = (e) => {
this.context.dispatch('ADD_ITEM', {name:'Marvin'});
}