ReactJS与ES6:当我传达两个组件时,this.props不是一个函数

sko*_*ozz 23 ecmascript-6 reactjs

我正在和ES6一起使用ReactJS,但是我通过道具来传达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>
  }
}
Run Code Online (Sandbox Code Playgroud)

这回来了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

kno*_*ody 14

您在构造函数中缺少绑定,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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)


Fel*_*ner 6

当你使用React.createClass()时,它会自动为你的函数绑定到它.

由于您使用的是ES6类语法,因此您需要自己进行这些绑定.这有两个选择:

render() {
    return <div>
      <SearchBar filterUser={this.filterUser.bind(this)} />
      <span>Value: {this.state.filter}</span>
    </div>
  }
Run Code Online (Sandbox Code Playgroud)

或者您可以将它绑定在您的构造函数上,如下所示:

constructor(props) {
    super(props);
    this.state = {name: '', age: '', filter: ''};
    this.filterUser = this.filterUser.bind(this);
  } 
Run Code Online (Sandbox Code Playgroud)

您可以在以下文档中阅读:https://facebook.github.io/react/docs/reusable-components.html#es6-classes

请注意,这两个选项是互斥的.