简体   繁体   中英

How to share a data between child and parent component in React?

I have two components (Table component & User component) in my react app. I have several users data in a table in my one component. I need to pass a user id from the Table component to the User component when click on a button. The problem is when I call the property from the table component, it appears this.props.onClick is not a function error in console. How can I solve this?

Table component:

class EnhancedTable extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      userID: 10
    };
    this.sendUserId = this.sendUserId.bind(this);
  }

  sendUserId() {
    this.props.onClick(this.state.userID);
  }
  render() {
    return (
       <button onClick={this.sendUserId}>
           <BorderColorIcon className="action margin-r" />
       </button>
    )
  }
}

User component:

Import EnhancedTable from './EnhancedTable';

class Users extends Component {

  constructor(props) {
    super(props);
    this.state = {
      userID: 5
    };
    this.onFillForm = this.onFillForm.bind(this);
   }

  onFillForm(idd) {
    this.setState({
      userID : idd
    })
  }

  render() {
     return(
         <span onClick = {this.onFillForm} className="mainUserDivTitle">{this.state.userID}</span>
     )
   }
}

Assumption: EnhancedTable is child component and User is parent component.

Problem with your code: you have not called Child component, hence EnhancedTable is not getting this.props.onClick .

You need to call EnhancedTable like this:

<EnhancedTable onClick = {this.onFillForm} />

You need to call <EnhancedTable /> instead of <span />

In the User component

import React, { Component } from 'react';

import EnhancedTable from './EnhancedTable';

class Users extends Component {

  constructor(props) {
    super(props);
    this.state = {
      userID: 5
    };
    this.onFillForm = this.onFillForm.bind(this);
   }

  onFillForm(idd) {
    this.setState({
      userID : idd
    })
  }

  render() {
     return(
         <>
           <div className="mainUserDivTitle">{this.state.userID}</div>
           <EnhancedTable onClick={this.onFillForm} />
         </>
     )
   }
}

export default Users;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM