首页 > 解决方案 > 如何从子组件调用父组件中的函数

问题描述

我有一个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()}
            />
      );
  }

标签: javascriptreactjscomponentsreact-state

解决方案


您可以用另一个组件包装RenderItem组件然后渲染它,

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

renderItemofReactiveList将是:renderItem={Wrapper(this.addFunc)} 那么RenderItem组件将是

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

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


推荐阅读