【问题标题】:How to get react-pose working with class components?如何让反应姿势与类组件一起工作?
【发布时间】:2019-04-10 20:56:07
【问题描述】:

我关注了the documentationthis blog post,但我一直在努力让任何事情发挥作用。

在本地,我收到以下错误:HEY, LISTEN! No valid DOM ref found. If you're converting an existing component via posed(Component), you must ensure you're passing the ref to the host DOM node via the React.forwardRef function.

所以我尝试转发参考:

class ColorCheckbox extends Component {
  setRef = ref => (this.ref = ref);

  constructor(props) {
    super(props);
  }

  render() {
    const { key, children, color } = this.props;
    return (
      <button
        ref={this.setRef}
        key={key}
        style={{
          ...style.box,
          background: color,
        }}
      >
        {children}
      </button>
    );
  }
}

export default forwardRef((props, innerRef) => (
  <ColorCheckbox ref={innerRef} {...props} />
));

我可以在我的父组件中 console.log ref 工作:

ColorCheckbox {props: Object, context: Object, refs: Object, updater: Object, setRef: function ()…} "ref"

但是,我仍然收到No valid DOM ref found... 的消息(上图)。

Here's a simple Codesandbox describing my issue.

关于 Codesandbox:

我在此沙盒中遇到跨域错误(它们不会在本地发生)。如果您将第 14 行更改为 ColorCheckbox,则会出现跨域错误...

有什么想法吗?

【问题讨论】:

    标签: javascript reactjs animation react-pose


    【解决方案1】:

    当您在基于类的组件上调用 forwardRef 并尝试通过 ref 属性传递 ref 时,它将不起作用。文档示例仅适用于常规 DOM 元素。而是尝试执行以下操作:

    export default forwardRef((props, innerRef) => (
      <ColorCheckbox forwardRef={innerRef} {...props} />
    ));
    

    我刚刚使用了一个任意名称,因此在本例中为 forwardRef,将 ref 作为道具传递。在您基于类的组件中,我已将按钮上设置 ref 的部分更改为:

    const { key, children, selected, color, forwardRef } = this.props;
    return (
      <button
        ref={forwardRef}
        key={key}
        style={{
        ...
    

    他们在博客文章中介绍的以下方法仅适用于常规 DOM 元素和样式化组件:

    const MyComponent = forwardRef((props, ref) => (
      <div ref={ref} {...props} />
    ));
    

    请参阅我的Codesandbox fork 以查看一个工作示例。

    【讨论】:

    • 感谢您的详细解答! ?知道为什么会出现跨域错误吗?
    • @A7DC React 文档提到从 CDN 加载库时可能会发生这种情况,这可能与 Codesandbox 在我们添加的库中的加载方式有关。如果其中一个库抛出错误,则会显示为跨域错误。
    • 很高兴能帮上忙 (:
    猜你喜欢
    • 2017-07-29
    • 1970-01-01
    • 2022-08-16
    • 2021-09-24
    • 2023-02-02
    • 2017-06-25
    • 2020-12-13
    • 2012-02-02
    • 2011-02-22
    相关资源
    最近更新 更多