如何让 react-pose 与 class 组件一起工作?

How to get react-pose working with class components?

我关注了 the documentation and this 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.

关于代码沙盒:

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

有什么想法吗?

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

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

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

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

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

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

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