javascript - 如何从子组件调用父组件中的函数
问题描述
我有一个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()}
/>
);
}
解决方案
您可以用另一个组件包装RenderItem
组件然后渲染它,
const Wrapper = cb => {
return (res, triggerClickAnalytics) => (
<RenderItem
res={res}
triggerClickAnalytics={triggerClickAnalytics}
addFunc={cb}
/>
);
};
和renderItem
ofReactiveList
将是:renderItem={Wrapper(this.addFunc)}
那么RenderItem
组件将是
const RenderItem = ({ res, triggerClickAnalytics, addFunc }) => {
...
见沙箱:https ://codesandbox.io/s/autumn-paper-337qz?fontsize=14&hidenavigation=1&theme=dark
推荐阅读
- javascript - 尝试在 2 类 CSS/HTML 之间切换以获得整洁的动画
- cgal - 如何精确偏移一个圆段多边形
- javascript - 类型:类由抽象类扩展
- python - 如何使用python在excel中找到某个COLUMN的第一个空白行
- java - Android / Firebase,获取当前时间戳
- prolog - 序言:乘法(X,Y)
- java - java.io.FileNotFoundException:/sdcard/...:打开失败:EISDIR(是一个目录)
- vhdl - 将 12 个向量加在一起只是为了在模拟中未定义所有输入和输出
- layout - ScrollingView 高度可编辑 Xamarin.ios [已解决]
- db2 - PaaS 离线时的 DB2 吞吐量?