简体   繁体   English

从作为道具接收的组件访问父方法

[英]Accessing parent method from a component received as a prop

I'm trying to build a reusable Confirmation component that renders a button and when clicked, it should open a Material UI Dialog.我正在尝试构建一个可重用的 Confirmation 组件,该组件呈现一个按钮,并在单击时打开一个 Material UI 对话框。 The button component gets passed in as a prop for the Confirmation component按钮组件作为 Confirmation 组件的 prop 传入

<Confirmation component={() => <MUIButton>Click me</MUIButton>} />

The parent component looks like this父组件看起来像这样

const Confirmation = ({ component: Component }) => {

  const handleClick = () => {
    ...logic to open the dialog...
  }

  return (
    <>
      <Component onClick={handleClick} <-- how to trigger this? />
      <Dialog />
    </>
  )
}

Now how would I get this to work without having to specify the onClick in the passed button component itself?现在我如何让这个工作而不必在传递的按钮组件本身中指定onClick For this situation one can assume the component passed as a prop is always some kind of a button.对于这种情况,可以假设作为道具传递的组件始终是某种按钮。

<Confirmation
  component={() => (
    <MUIButton
      onClick={...logic} <-- don't want to have to specify this
    >
      Click me
    </MUIButton>
  )
/>

OR am I approaching this from a wrong perspective?或者我是从错误的角度看待这个问题? Should this be solved by passing the button as a child instead?这是否应该通过将按钮作为子项传递来解决? As in

<Confirmation>
  <MUIButton> Click me </MUIButton>
</Confirmation>

and how would the implementation be in this situation?在这种情况下将如何实施?

Thank you in advance!先感谢您!

Ended up solving this by creating a higher order component as suggested by John最终通过按照约翰的建议创建一个高阶组件来解决这个问题

const withConfirmation = (WrappedComponent) => {
  return (props) => {
    return (
      <>
        <WrappedComponent

          // Overrides the possible onClick logic passed as a prop
          onClick={ ...dialog opening logic }

          {...props}
        />
        <Dialog>
          ...
        </Dialog>
      </>
    );
  };
};
const Confirmation = withConfirmation(MuiButton)

<Confirmation>Clicking me opens a dialog</Confirmation>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM