[英]React.forwardRef Causes Error with Styled Component
I am running React 16.3.1 and Styled Components 3.2.5 currently and am hitting an issue trying to use React.forwardRef. 我目前正在运行React 16.3.1和Styled Components 3.2.5,并试图使用React.forwardRef。
I have an Input component that is comprised of a wrapper div that holds the label and input field. 我有一个Input组件,它由一个包含标签和输入字段的包装div组成。 However, I want to be able to forward a ref directly to the input field and not have to traverse to it via the primary wrapping div. 但是,我希望能够将ref直接转发到输入字段,而不必通过主包装div遍历它。
const Input = React.forwardRef((props, ref) => (
<Wrapper>
<Label htmlFor={props.id} required={props.required}>
{props.label}
</Label>
<InputField
id={props.id}
...
/>
</Wrapper>
));
That is a simplified version of my component. 这是我的组件的简化版本。 However, this creates the following error: 但是,这会产生以下错误:
Uncaught Error: Cannot create styled-component for component: [object Object]
Maybe upgrading Styled Components to v4 would help? 也许将Styled Components升级到v4会有帮助吗? But is there any solution before upgrading that I haven't found yet? 但升级之前是否有任何解决方案尚未找到?
Thank you. 谢谢。
As explained in related issue , there is blocking React Redux issue that is expected to be closed with this PR . 正如相关问题中所解释的那样,阻止React Redux问题 ,预计将通过此PR关闭。
A workaround is to use an approach that was used before React 16.3 forwardRef
and use custom prop instead of ref
to forward refs: 解决方法是使用在React 16.3 forwardRef
之前使用的方法,并使用自定义prop而不是ref
来转发refs:
const Input = ({forwardRef, ...props}) => (
<Wrapper>
<Label htmlFor={props.id} required={props.required}>
{props.label}
</Label>
<InputField
ref={forwardRef}
id={props.id}
...
/>
</Wrapper>
));
Why <Wrapper {...rest}>
? 为什么<Wrapper {...rest}>
?
I thing pass ref to Wrapper is a correct way: 我的事情传递给Wrapper是一个正确的方法:
<Wrapper ref={ref}>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.