小智 5

是的,您可以通过多种方式将一个组件作为 props 传递给另一个组件。

\n

第一种方式,

\n
function Wrapper({button: Button}) {\n  return (\n    <div\n      style={{\n        display: \'flex\',\n        alignItems: \'center\',\n        justifyContent: \'center\',\n      }}\n    >\n      <Button />\n    </div>\n  );\n}\n\nexport default function App() {\n  const Button = () => {\n    return <button onClick={() => console.log(\'button clicked\')}>Click</button>;\n  };\n\n  // \xef\xb8\x8f pass button as props to the Wrapper component\n  return (\n    <div>\n      <Wrapper button={Button} />\n    </div>\n  );\n}\n
Run Code Online (Sandbox Code Playgroud)\n

在上面的示例中,一个组件作为 prop 传递给子组件。\nWrapper 组件必须将 prop 从 Button 重命名为 Button(首字母大写),因为所有组件名称都必须以大写字母开头。

\n

第二种方式,

\n
function Wrapper({button}) {\n  return (\n    <div\n      style={{\n        display: \'flex\',\n        alignItems: \'center\',\n        justifyContent: \'center\',\n      }}\n    >\n      {button}\n    </div>\n  );\n}\n\nexport default function App() {\n  const Button = ({text}) => {\n    return (\n      <button onClick={() => console.log(\'button clicked\')}>{text}</button>\n    );\n  };\n\n  return (\n    <div>\n      <Wrapper button={<Button text="Some button text" />} />\n    </div>\n  );\n}\n
Run Code Online (Sandbox Code Playgroud)\n

在这个例子中,我们在将 Button 组件传递给 Wrapper 组件时直接设置了 Button 组件的 props。\n我们没有传递实际的组件函数,而是传递 Button 组件的返回值。\n这意味着我们有将 prop 用作 {button},而不是在我们的 Wrapper 组件中。

\n

现在您可以使用上述两种方法中的任何一种来更改代码,我在这里使用第二种方法

\n
const AgriReactTable = ({agentDetailsDialogBox, URL, columnDefs, reload}) => {\n\n     return (\n          <div>\n              {agentDetailsDialogBox}\n          </div>\n     )\n}\n\n\nconst App = () => {\n      const [reload, setReload] = useState()\n      const AgentDetailsDialogBox = () => { return <div>{someContent}</div>}\n      \n      return (\n         <div>\n             <AgriReactTable agentDetailsBox={<AgentDetailsBox reload={setReload} URL={apis.ADMIN_ALL_AGENT} columnDefs={columnDef} reload={reload}/>} />\n         </div>\n      )\n}\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n