【问题标题】:How to pass down props to function in ReactJS如何将道具传递给 ReactJS 中的函数
【发布时间】:2020-10-10 19:14:07
【问题描述】:

我的主类中有一个名为selectedData 的数组作为状态。这个类调用了一个名为Wrapper的组件,而Wrapper调用了一个名为RenderItem的函数式组件。我希望能够在我的RenderItem 函数中使用selectedData 数组。

我知道这可能不是调用该函数的最有效方式,但我正在使用一个名为 ReactiveSearch 的开源 UI 来显示我的搜索结果,到目前为止,我设法让它工作的唯一方法是调用 Wrapper,然后调用 RenderItem。我想尽可能避免改变它。

我的代码摘要如下:


const Wrapper = (props) => {
  return (res, triggerClickAnalytics, selectedData) => (
    <RenderItem
      res={res}
      triggerClickAnalytics={triggerClickAnalytics}
      addFunc={props}
      selectedData={props.selectedData}
    />
  );
};
class Search extends Component {
  constructor(props) {
    super(props);
    this.addFunc = this.addFunc.bind(this);
    this.state = { selectedData:[] }
  }
  addFunc(resultdata) {
   (some function)
  }

  render() {
    return (
          <ReactiveList
            componentId="results"
            dataField="_score"
            size={10}
            renderItem={Wrapper(this.addFunc, this.state.selectedData )}
          />
    );
  }
}

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

  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 (
      <input type='checkbox' onChange={() => addFunc(resultdata)}/>
  );
};
  

如您所见,我尝试将 props 传递给 Wrapper,但我仍然无法在 WrapperRenderItem 内调用 selectedData。 任何帮助将不胜感激。

【问题讨论】:

  • 您好,wrapperRenderItem 的具体交互方式,请在代码中显示,谢谢。

标签: javascript reactjs state react-props


【解决方案1】:

renderItem={Wrapper(this.addFunc, this.state.selectedData )} 您不能以这种方式将道具传递给子组件。 你可以像这样传递道具

<Wrapper 
  addFunc={this.addFunc}
  selectedData={this.selectedData}
 />

【讨论】:

    猜你喜欢
    • 2022-10-21
    • 1970-01-01
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-13
    • 1970-01-01
    相关资源
    最近更新 更多