繁体   English   中英

反应 | ForwardedRef 使用 React.Component

[英]React | ForwardedRef using React.Component

我正在 React 中创建自定义组件,我需要使用 forwardedRef 导出它。 但是当我尝试时,出现了这个错误:

错误

my code:

export interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement>{
  ref?: React.RefObject<HTMLButtonElement>;
}

class Button extends React.Component<ButtonProps> {

  render() {
    const {
      ref,
      children,
      ...otherProps
    } = this.props;
    return (
      <button 
        {...otherProps} 
        ref={ref}
      >
        {children}
      </button>
    )
  }
}

const ButtonForwarded = React.forwardRef<ButtonProps>((props, ref) => 
<Button {...props} ref={ref} /> );

ButtonForwarded.displayName = 'Button';

export default ButtonForwarded;

像这样创建ButtonForwarded组件:

const ButtonForwarded = React.forwardRef((props: ButtonProps, ref: LegacyRef<Button>) => <Button {...props} ref={ref} /> );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM