trigger icon indicating copy to clipboard operation
trigger copied to clipboard

Warning: Function components cannot be given refs

Open jackiehluo opened this issue 6 years ago • 3 comments

Getting this error on the latest alpha (4.0.0-alpha.5):

Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

    Check the render method of `Trigger`.

Looks like an issue from converting from class components to functional components?

jackiehluo avatar Nov 13 '19 21:11 jackiehluo

I worked around this by first determining if the child is functional using this check. You can obviously skip this if you already know for sure that the child will be a functional component:

function isFunctional(component) {
  return (
    typeof component === "function" &&
    !(component.prototype && component.prototype.isReactComponent)
  );
}

And then if it is a functional component, I just ignore the ref like this:

const IgnoreRef = React.forwardRef((props, ref) => {
  const child = React.Children.only(props.children) as React.ReactElement;
  return React.cloneElement(child, { ...props, ...child.props });
}) as any;

...

<Trigger ... >
  <IgnoreRef>
    <MyComponent ... />
  </IgnoreRef>
</Trigger>

It would be nice though if rc-trigger could do something like this internally so we don't have to worry about it.

mogzol avatar Dec 09 '19 20:12 mogzol

Made a PR to fix this: https://github.com/react-component/trigger/pull/156

mogzol avatar Dec 10 '19 06:12 mogzol

same issue https://github.com/ant-design/ant-design/issues/21873

afc163 avatar Mar 04 '20 13:03 afc163