简体   繁体   中英

How to pass down props to function in ReactJS

I have an array called selectedData as a state in my main Class. This class calls a component called Wrapper , and the Wrapper calls a functional component called RenderItem . I want to be able to use the selectedData array within my RenderItem function.

I know this might not be the most efficient way of calling the function, but I am using an open-source UI called ReactiveSearch to display results from my search, and the only way I managed to make it work till now is by calling Wrapper and then RenderItem. I would like to avoid changing this as much as possible.

A summary of my code is below:


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

As you can see, I tried passing in props to my Wrapper, but I still can't call the selectedData within my Wrapper or within my RenderItem . Any help will be really appreciated.

renderItem={Wrapper(this.addFunc, this.state.selectedData )} you cannot pass props to child components this way. You can pass Props like this

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

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