[英]How to use props as component?
我有一個組件,我在其中接收包含 Link 組件(React 路由器,但可以是任何東西)的道具:
children: [
{
id: '1',
isActive: false,
label: 'Forms',
icon: <DestinationsIcon height={30} width={30} />,
link: <Link to={'somewhere'} />,
},
然后在接收這些道具的組件中,我可以從孩子那里提取道具:
<List>
{React.Children.map(children, (child) => {
if (!React.isValidElement(child)) {
return null;
}
return React.cloneElement(child, {
children: <div>{child.props.label}</div>,
});
})}
</List>
例如, child.props.label
確實返回了正確的 label。 但是我想做的是用link
道具替換包裝<div>
,如下所示:
children: <child.props.link>{child.props.label}</child.props.link>,
這當然行不通。 如果我正在嘗試使用 React.createElement:
children: React.createElement(child.props.link),
第一個參數應該是一個字符串,但我正在傳遞一個組件。 問題是我必須從外部接收帶有自己上下文的 Link 組件,並且我無法重新創建它,否則我可以避免所有復雜性。
有誰知道將鏈接道具呈現為 JSX 包裝器的正確方法是什么?
您的link: <Link to={'somewhere'} />
道具不是一個組件,它是一個元素。 這就是它作為一個組件的樣子: link: Link
(然后你需要單獨傳遞Link
的 props,也許是linkProps
):
children: [
{
id: '1',
isActive: false,
label: 'Forms',
icon: <DestinationsIcon height={30} width={30} />,
link: Link, // ***
linkProps: {to: 'somewhere'}, // ***
},
然后,要使用它,您需要通過帶有大寫第一個字符的標識符來引用它,因為這就是 React/JSX 區分標簽(如div
或svg
)和組件的方式。
所以沿着這些思路:
const Link = child.props.link;
return React.cloneElement(child, {
children: <Link {...child.props.linkProps}>{child.props.label}</Link>,
});
...雖然這可能需要調整,因為我不清楚你為什么要進行提取和克隆。
這是一個更簡單的示例,顯示使用組件作為道具:
const { useState } = React; const Example = ({ link: Link, linkProps, label }) => { return <Link {...linkProps}>{label}</Link>; }; const SomeNiftyLink = ({ href, className, children }) => ( <a href={href} className={className}> {children} </a> ); const App = () => { return ( <Example link={SomeNiftyLink} linkProps={{ href: "#somewhere", }} label="The label" /> ); }; const root = ReactDOM.createRoot(document.getElementById("root")); root.render(<App />);
<div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.