[英]React cloneElement is not working for functional component
我想使用{React.cloneElement(<MyComponent />, { onClick: () => console.log('click'), style: {background: 'red'} })}
添加一些道具到我的組件中
完整代碼:
const MyComponent = () => {
return (
<div>
foooo
</div>
);
};
....
return React.cloneElement(<MyComponent />, { onClick: () => console.log('click'), style: {background: 'red'} })
但是props
沒有傳遞到我的組件中。
當我使用:
return React.cloneElement(<div>foooo</div>, { onClick: () => console.log('click'), style: {background: 'red'} })
道具正在發揮作用。 為什么? 我不明白為什么。
當 JSX 可用時,為什么要使用cloneElement
(可以從MyComponents
語法中得出結論)。
而是這樣做:
<MyComponent
onClick={() => console.log("click")}
style={{ background: "red" }}
/>
並修復您的組件:
const MyComponent = ({ style, onClick }) => {
return <div onClick={onClick} style={style}>foooo</div>;
}
JSX是createElement
/ cloneElement
語法糖。
React.cloneElement(
element,
[props],
[...children]
)
React.cloneElement() 幾乎等同於:
<element.type {...element.props} {...props}>{children}</element.type>
因此正確的語法:
const onClick = () => console.log('click');
const style = {background: 'red'};
// Exatcly the same effect as <MyComponent .../> above
React.cloneElement(<MyComponent/>, {onClick, style}, null);
您需要在組件中應用 props:
export const Test = (props: any) => {
return (<button {...props}>Click Me</button>);
}
在這種情況下,您可以使用設置道具
React.cloneElement(<MyComponent/>, props, null);
但是我不建議克隆(太重了)我認為最好在props中使用特殊的render函數:
export const Wrapper = (props: {render: (props: any) => any}) => {
const childProps = {style: {background: 'red'}, onClick: () => { console.log('click'); }};
if (props.render){
return props.render(childProps);
} else {
return <></>;
}
}
// ...
// usage:
export default function App() {
return (
<div className="App">
<Wrapper render={(props)=>{
return <button {...props}>TEST</button>;
}}/>
</div>
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.