我正在使用带有ES6的ReactJS,但是在通过props交流child> parent时遇到一些问题。我的方法示例:
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。
Uncaught TypeError: this.props.filterUser is not a function
任何想法?绑定也许?
[编辑]解决方案(感谢@knowbody和@Felipe Skinner):
我在构造函数中缺少绑定。在SearchBar构造函数中的绑定可以完美地工作。
使用React.createClass()(ES5),它会自动this为您的功能进行绑定。在ES6中,您需要this手动绑定。更多信息https://facebook.github.io/react/docs/reusable- components.html#es6-classes
React.createClass()
this
您缺少构造函数中的绑定,props如果您没有在构造函数中使用它们,也不需要通过。另外你还需要import { PropTypes } from 'react'
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> ); } }