我有一個組件,我在其中接收包含 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它確實回傳了正確的標簽。但是我想做的是用道具替換包裝<div>,link如下所示:
children: <child.props.link>{child.props.label}</child.props.link>,
這當然行不通。如果我正在嘗試使用 React.createElement:
children: React.createElement(child.props.link),
第一個引數應該是一個字串,但我正在傳遞一個組件。問題是我必須從外部接收帶有自己背景關系的 Link 組件,并且我無法重新創建它,否則我可以避免所有復雜性。
有誰知道將鏈接道具呈現為 JSX 包裝器的正確方法是什么?
uj5u.com熱心網友回復:
你的link: <Link to={'somewhere'} />道具不是一個組件,它是一個元素。這就是它作為一個組件的樣子:(link: Link然后你需要Link單獨傳遞道具,也許是linkProps):
children: [
{
id: '1',
isActive: false,
label: 'Forms',
icon: <DestinationsIcon height={30} width={30} />,
link: Link, // ***
linkProps: {to: 'somewhere'}, // ***
},
然后,要使用它,您需要通過帶有大寫首字符的識別符號來參考它,因為這就是 React/JSX 區分標簽(如divor 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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/505621.html
標籤:javascript 反应
