[英]Clone a React component that implements forwardRef
Lets say I have a base component that uses forwardRef
like so:假设我有一个使用
forwardRef
的基本组件,如下所示:
const BaseMessage = React.forwardRef((props, ref) => (
<div ref={ref}>
{props.icon}
<h2>{props.title}</h2>
<p>{props.message}</p>
</div>
)
Now I want to create a second component, ErrorMessage
that is essentially a copy of the BaseMessage
but with a predefined value for props.icon
, such that the icon
prop is not needed to be set.现在我想创建第二个组件,
ErrorMessage
,它本质上是BaseMessage
的副本,但具有props.icon
的预定义值,因此不需要设置icon
prop。 Otherwise, its an exact copy of BaseMessage
.否则,它是
BaseMessage
的精确副本。
<ErrorMessage title="Oops!" message="Something went wrong when submitting the form. Please try again." />
I don't want to have to do this, since it feels weird to have two layers of forwardRef
going on here:我不想这样做,因为在这里有两层
forwardRef
感觉很奇怪:
const ErrorMessage = React.forwardRef(({icon, ...props}, ref) => (
<BaseMessage ref={ref} icon={<svg></svg>} {...props} />
))
Is there a way I can make a clone/copy of BaseMessage
without having to reimplement forwardRef
for ErrorMessage
as well?有没有一种方法可以制作
BaseMessage
的克隆/副本,而不必为ErrorMessage
重新实现forwardRef
? I know there are utils out there like withProps
from recompose
but I'd like to avoid using a library if I can.我知道有一些实用工具,比如
recompose
中的withProps
,但如果可以的话,我想避免使用库。
Try cloneElememt尝试克隆元素
React.cloneElement(BaseMessage, { icon: '' })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.