Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
509 views
in Technique[技术] by (71.8m points)

ecmascript 6 - ReactJS with ES6: this.props is not a function when I communicate two components

I'm working with ReactJS with ES6, but I have some problems to communicate child > parent through props. Example of my approach:

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>
  }
}

This returns Uncaught TypeError: this.props.filterUser is not a function.

Any idea? Binding maybe?

[EDIT] Solution (Thanks @knowbody & @Felipe Skinner):

I was missing binding in my constructor. Binding in the SearchBar constructor works perfectly.

Using React.createClass() (ES5), it automatically does bindings to this for your functions. In ES6 you need bind this manually. More info https://facebook.github.io/react/docs/reusable-components.html#es6-classes

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are missing binding in your constructor, also you don't need to pass props if you are not using them in the constructor. Also you need to 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>
    );
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...