How to call function in parent component from the child component

拜拜、爱过 提交于 2020-06-29 03:59:32

问题


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()}
            />
      );
  }

回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/62455038/how-to-call-function-in-parent-component-from-the-child-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!