问题
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