我正在使用ReactJS和ES6,但是我在通过props通信子组件和父组件方面遇到了一些问题。以下是我的一种方法示例:
class SearchBar extends React.Component {
handler(e){
this.props.filterUser(e.target.value);
}
render () {
return <div>
<input type='text' className='from-control search-bar' placeholder='Search' onChange={this.handler} />
</div>
}
}
export default class User extends React.Component {
constructor(props) {
super(props);
this.state = {name: '', age: '', filter: ''};
}
filterUser(filterValue){
this.setState({
filter: filterValue
});
}
render() {
return <div>
<SearchBar filterUser={this.filterUser} />
<span>Value: {this.state.filter}</span>
</div>
}
}
这个报错信息是 Uncaught TypeError: this.props.filterUser is not a function
。
有什么想法吗?可能需要绑定(Binding)吗?
[编辑] 解决方案(感谢 @knowbody 和 @Felipe Skinner):
我在构造函数中缺少绑定。在 SearchBar 构造函数中添加绑定之后完美解决。
使用 React.createClass()
(ES5),它会自动为您的函数进行 this
绑定。 在 ES6 中需要手动绑定 this
。更多信息请参见https://facebook.github.io/react/docs/reusable-components.html#es6-classes
SearchBar.propTypes = { filterUser: React.PropTypes.func };
更好。 - skozz