gpt4 book ai didi

javascript - React cloneElement 不适用于功能组件

转载 作者:行者123 更新时间:2023-12-05 02:08:29 29 4
gpt4 key购买 nike

我想使用 {React.cloneElement(<MyComponent />, { onClick: () => console.log('click'), style: {background: 'red'} })} 向我的组件添加一些 Prop

完整代码:

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'} })

Prop 正在发挥作用。为什么?我不明白为什么。

最佳答案

当 JSX 可用时,为什么要使用 cloneElement(可以从 MyComponents 语法中得出结论)。

改为:

<MyComponent
onClick={() => console.log("click")}
style={{ background: "red" }}
/>

并修复你的组件:

const MyComponent = ({ style, onClick }) => {
return <div onClick={onClick} style={style}>foooo</div>;
}

JSX is sugar syntax对于 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);

Edit intelligent-architecture-9modf

关于javascript - React cloneElement 不适用于功能组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60844971/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com