【发布时间】:2022-01-11 17:14:26
【问题描述】:
我在 React 中使用组合并想调用父方法。我发现的所有示例都使用继承。
容器组件 - 插入子组件
interface ContainerProps {
children: ReactNode;
}
function Container(props: ContainerProps) {
const [showApply, setShowApply] = useState<boolean>(false);
return (
<>
<div>Children</div>
{props.children}
</>
);
// I want to call this method from the `children`
function calledByChild(){}
}
组合 - 点击按钮时需要调用Container方法
function CombinedComponent() {
return <Container handleApplyClicked={handleApplyClicked}>
<Button type="primary" shape="round" onClick={tellContainerThatButtonWasClicked}>
</Container >
}
当单击CombinedComponent 中的按钮时,我希望它通知Container。我见过的示例使用继承并将父母方法传递给孩子,但在这种情况下,孩子正在其中定义父母。
如何做到这一点?
更新
我尝试将它添加到父组件,但子组件似乎没有添加额外的属性。
{React.cloneElement(props.children as React.ReactElement<any>, { onClick: myFunc })}
子界面/道具
interface CombinedComponentProps{
// This value is always undefined
onClick?: () => void;
}
function CombinedComponent(props: CombinedComponentProps) {
...
// Undefined
console.log(props.onClick)
}
【问题讨论】:
标签: javascript reactjs typescript