我正在使用ReactJS与ES6一起工作,但我在通过道具与孩子>家长沟通时遇到了一些问题。我的方法的例子:
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。
有什么想法吗?也许是捆绑?
编辑解决方案(谢谢@knowbody & @Felipe ):
构造函数中缺少绑定。SearchBar构造函数中的绑定工作得很好。
使用React.createClass() (ES5),它会自动为您的函数进行this绑定。在ES6中,您需要手动绑定this。更多信息https://facebook.github.io/react/docs/reusable-components.html#es6-classes
发布于 2015-06-30 15:01:51
构造函数中缺少绑定,如果在构造函数中没有使用绑定,也不需要传递props。同时你也需要import { PropTypes } from 'react'
class SearchBar extends React.Component {
constructor() {
super();
this.handler = this.handler.bind(this);
}
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() {
super();
this.filterUser = this.filterUser.bind(this);
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>
);
}
}发布于 2015-06-30 14:54:38
当您使用React.createClass()时,它会自动为您的函数进行绑定。
由于您使用的是ES6类语法,所以您需要自己完成这些绑定。以下是两个选择:
render() {
return <div>
<SearchBar filterUser={this.filterUser.bind(this)} />
<span>Value: {this.state.filter}</span>
</div>
}也可以将其绑定到构造函数上,如下所示:
constructor(props) {
super(props);
this.state = {name: '', age: '', filter: ''};
this.filterUser = this.filterUser.bind(this);
} 您可以在docs:https://facebook.github.io/react/docs/reusable-components.html#es6-classes上看到这方面的内容。
注意到这两个选项是相互排斥的.
发布于 2019-04-19 12:43:01
在我的例子中,我以错误的方式导入了组件。我有组件"HomeAdmin“和”寄存器“。
我在HomeAdmin.js:import { Register } from "/path/to/register"上有这个
更改为此并工作:import Register from "/path/to/register"
https://stackoverflow.com/questions/31141444
复制相似问题