简体   繁体   中英

How to pass a component with props to another component as props in react

将带有 prop reload 的 AgentDialogBox 传递给 AgGridReactTable 组件

Yes, you can pass a component as props to another component in various ways.

First way,

function Wrapper({button: Button}) {
  return (
    <div
      style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      <Button />
    </div>
  );
}

export default function App() {
  const Button = () => {
    return <button onClick={() => console.log('button clicked')}>Click</button>;
  };

  // 👇️ pass button as props to the Wrapper component
  return (
    <div>
      <Wrapper button={Button} />
    </div>
  );
}

In the above example, a component is passed as a prop to a child component. The Wrapper component had to rename the prop from button to Button (capital first letter) because all component names must start with a capital letter.

Second Way,

function Wrapper({button}) {
  return (
    <div
      style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      {button}
    </div>
  );
}

export default function App() {
  const Button = ({text}) => {
    return (
      <button onClick={() => console.log('button clicked')}>{text}</button>
    );
  };

  return (
    <div>
      <Wrapper button={<Button text="Some button text" />} />
    </div>
  );
}

In this example, we directly set the props of the Button component when passing it to the Wrapper component. We are not passing the actual component function, instead, we are passing the return value of the Button component. This means that we have to use the prop as {button}, instead of in our Wrapper component.

Now you can change your code using any of the above 2 mentioned ways, I'm using the second way here

const AgriReactTable = ({agentDetailsDialogBox, URL, columnDefs, reload}) => {

     return (
          <div>
              {agentDetailsDialogBox}
          </div>
     )
}


const App = () => {
      const [reload, setReload] = useState()
      const AgentDetailsDialogBox = () => { return <div>{someContent}</div>}
      
      return (
         <div>
             <AgriReactTable agentDetailsBox={<AgentDetailsBox reload={setReload} URL={apis.ADMIN_ALL_AGENT} columnDefs={columnDef} reload={reload}/>} />
         </div>
      )
}

Reference -> https://bobbyhadz.com/blog/react-pass-component-as-prop#:~:text=You%20can%20pass%20a%20component,assigned%20to%20the%20children%20prop .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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