简体   繁体   中英

How to call function in parent component from the child component

I have a function called addFunc in my main Class. This class calls the RenderItem function to display a list of items. Each item has an onClick that should execute the addFunc function.

I am unable to call the addFunc function from within my RenderItem function because they are in different components. How do I get past this?

This is a summary of my code:

const selectedData = []

class Search extends Component {
    constructor(props) {
      super(props);
      this.addFunc = this.addFunc.bind(this);
    }

    addFunc(resultdata){
        console.log(resultdata)
        selectedData = [...selectedData, resultdata]
        console.log(selectedData)
      };
    render() {
      return (
            <ReactiveList
            componentId="results"
            dataField="_score"
            pagination={true}
            react={{
                and: ["system", "grouping", "unit", "search"]
            }}
            size={10}
            noResults="No results were found..."
            renderItem={RenderItem}
            />
      );


const RenderItem = (res, addFunc) => {
    let { unit, title, system, score, proposed, id } = {
      title: "maker_tag_name",
      proposed: "proposed_standard_format",
      unit: "units",
      system: "system",
      score: "_score",
      id: "_id"
    };
    const resultdata = {id, title, system, unit, score, proposed}

      return (
            <Button
                shape="circle"
                icon={<CheckOutlined />}
                style={{ marginRight: "5px" }}
                onClick={this.addFunc()}
            />
      );
  }

You can wrap RenderItem component with another component and then render it,

const Wrapper = cb => {
  return (res, triggerClickAnalytics) => (
    <RenderItem
      res={res}
      triggerClickAnalytics={triggerClickAnalytics}
      addFunc={cb}
    />
  );
};

and renderItem of ReactiveList would be: renderItem={Wrapper(this.addFunc)} then RenderItem component would be

const RenderItem = ({ res, triggerClickAnalytics, addFunc }) => {
...

see sandbox: https://codesandbox.io/s/autumn-paper-337qz?fontsize=14&hidenavigation=1&theme=dark

You can pass a callback function defined in the parent as a prop to the child component

class Parent extends React.Component {
sayHello(name) => {
      console.log("Hello " + name)
}
render() {
        return <Child1 parentCallback = {this.sayHello}/>
    }
}

and then call it from the child component

class Child1 extends React.Component{
componentDidMount() {
   this.props.parentCallback("Foo")
}
render() { 
    return <span>child component</span>
    }
};

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