如何从子组件中调用父组件中的函数

时间:2020-06-18 16:40:38

标签: javascript reactjs components react-state

我的主类中有一个名为addFunc的函数。此类调用RenderItem函数以显示项目列表。每个项目都有一个onClick,应执行addFunc函数。

我无法从我的addFunc函数中调用RenderItem函数,因为它们位于不同的组件中。我该如何克服?

这是我的代码的摘要:

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

2 个答案:

答案 0 :(得分:1)

您可以将RenderItem组件与另一个组件包装在一起,然后进行渲染,

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

renderItem中的ReactiveList为:renderItem={Wrapper(this.addFunc)} 那么RenderItem组件就是

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

请参阅沙箱:https://codesandbox.io/s/autumn-paper-337qz?fontsize=14&hidenavigation=1&theme=dark

答案 1 :(得分:0)

您可以将父级中定义的回调函数作为道具传递给子级组件

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

然后从子组件中调用它

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