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

前端 未结 3 563
天涯浪人
天涯浪人 2020-11-30 04:40

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 Rea         


        
相关标签:
3条回答
  • 2020-11-30 05:29

    When ur using React.createClass(), it automatically does bindings to this for your functions.

    Since you're using the ES6 class syntax, you need to do those bindings by yourself. Here's two options:

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

    Or you could bind it on your constructor like this:

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

    You can read about this on the docs: https://facebook.github.io/react/docs/reusable-components.html#es6-classes

    Note that those two options are mutually exclusive.

    0 讨论(0)
  • 2020-11-30 05:30

    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>
        );
      }
    }
    
    0 讨论(0)
  • 2020-11-30 05:33

    In my case, I was importing the component the wrong way. I have the components "HomeAdmin" and "Register".

    I had this in HomeAdmin.js: import { Register } from "/path/to/register"

    Changed to this and worked: import Register from "/path/to/register"

    0 讨论(0)
提交回复
热议问题