最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React.forwardRef Causes Error with Styled Component - Stack Overflow

programmeradmin6浏览0评论

I am running React 16.3.1 and Styled Components 3.2.5 currently and am hitting an issue trying to use React.forwardRef.

I have an Input ponent that is prised of a wrapper div that holds the label and input field. 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.

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 ponent. However, this creates the following error:

Uncaught Error: Cannot create styled-ponent for ponent: [object Object]

Maybe upgrading Styled Components to v4 would help? But is there any solution before upgrading that I haven't found yet?

Thank you.

I am running React 16.3.1 and Styled Components 3.2.5 currently and am hitting an issue trying to use React.forwardRef.

I have an Input ponent that is prised of a wrapper div that holds the label and input field. 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.

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 ponent. However, this creates the following error:

Uncaught Error: Cannot create styled-ponent for ponent: [object Object]

Maybe upgrading Styled Components to v4 would help? But is there any solution before upgrading that I haven't found yet?

Thank you.

Share Improve this question edited Oct 23, 2018 at 8:11 DoomageAplentty asked Oct 23, 2018 at 7:49 DoomageAplenttyDoomageAplentty 2,7328 gold badges33 silver badges48 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

As explained in related issue, there is blocking React Redux issue that is expected to be closed with this 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:

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}>?

I thing pass ref to Wrapper is a correct way:

<Wrapper ref={ref}>
发布评论

评论列表(0)

  1. 暂无评论