如何从子组件中调用父组件中的函数 [英] How to call function in parent component from the child component
问题描述
我的主类中有一个名为 addFunc
的函数。此类调用 RenderItem
函数以显示项目列表。每个项目都有一个 onClick
,应执行 addFunc
函数。
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.
我无法从我的 RenderItem $ c内调用
addFunc
函数$ c>函数,因为它们位于不同的组件中。我该如何克服?
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?
这是我的代码摘要:
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()}
/>
);
}
推荐答案
您可以包装 RenderItem
组件和另一个组件,然后渲染它,
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}
/>
);
};
和 renderItem
> ReactiveList 将是: renderItem = {Wrapper(this.addFunc)}
然后是 RenderItem
组件将是
and renderItem
of ReactiveList
would be: renderItem={Wrapper(this.addFunc)}
then RenderItem
component would be
const RenderItem = ({ res, triggerClickAnalytics, addFunc }) => {
...
请参阅沙箱:> https://codesandbox.io/s/autumn-paper-337qz?fontsize=14& hidenavigation = 1& theme = dark
这篇关于如何从子组件中调用父组件中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!