我的主类中有一个名为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()}
/>
);
}
答案 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>
}
};