【问题标题】:React.forwardRef Causes Error with Styled ComponentReact.forwardRef 导致样式化组件出错
【发布时间】:2019-03-27 09:09:12
【问题描述】:

我目前正在运行 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 会有所帮助?但是升级前有没有我还没找到的解决方案呢?

谢谢。

【问题讨论】:

    标签: javascript reactjs ref styled-components forward-reference


    【解决方案1】:

    related issue 中所述,存在阻塞React Redux issue,预计将与this 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>
    ));
    

    【讨论】:

    • 非常感谢!我不得不稍微修改你的答案,因为我的 Styled Components 版本仍然期望“nnerRef”而不是ref。否则,我能够完成这项工作。
    【解决方案2】:

    为什么是&lt;Wrapper {...rest}&gt;

    我将 ref 传递给 Wrapper 是正确的方法:

    <Wrapper ref={ref}>
    

    【讨论】:

    • 抱歉,这是旧代码的继承。无关。但我不想将 ref 放在 Wrapper 上。我会在输入字段中需要它。
    猜你喜欢
    • 2020-02-29
    • 2022-01-26
    • 2021-11-03
    • 2023-02-09
    • 2020-02-24
    • 2011-03-13
    • 2021-09-12
    • 2020-06-16
    • 2021-12-01
    相关资源
    最近更新 更多