[英]React.forwardRef Causes Error with Styled Component
我目前正在运行React 16.3.1和Styled Components 3.2.5,并试图使用React.forwardRef。
我有一个Input组件,它由一个包含标签和输入字段的包装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>
));
这是我的组件的简化版本。 但是,这会产生以下错误:
Uncaught Error: Cannot create styled-component for component: [object Object]
也许将Styled Components升级到v4会有帮助吗? 但升级之前是否有任何解决方案尚未找到?
谢谢。
正如相关问题中所解释的那样,阻止React Redux问题 ,预计将通过此PR关闭。
解决方法是使用在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>
));
为什么<Wrapper {...rest}>
?
我的事情传递给Wrapper是一个正确的方法:
<Wrapper ref={ref}>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.