控制台中的React Forwardref警告问题

时间:2020-01-27 22:24:09

标签: reactjs typescript

嗨,我有以下代码。我想使用样式组件库在自己的材质ui按钮上设置样式:

import React from 'react';
import styled from 'styled-components'

import { Button as MuiButton } from '@material-ui/core';

interface SimpleProps<T extends string> {
  random?: T;
}

interface Props {
    children: React.ReactNode;
    isCircled?: boolean;
}

function StyledButton<T extends string>(
  props: Props & SimpleProps<T> & { ref?: React.Ref<HTMLButtonElement> }
) {
  type CombinedProps = Props & SimpleProps<T>;
  const Forwarded = styled(React.forwardRef<HTMLButtonElement, CombinedProps>(
    ({ children, isCircled, ...rest }, ref) => (
      <MuiButton ref={ref} {...rest}>
                {children}
            </MuiButton>
    )
    ))`
        background-color: green!important;
        border-radius: ${(props) => props.isCircled ? '25px' : '10px'}!important;
    `;
    return <Forwarded {...props} />
}

const Button: React.FC = (props: any) => {
    const { children } = props;
    const ref = React.useRef<HTMLButtonElement>(null);

    return (
        <StyledButton ref={ref}>
            {children}
        </StyledButton>
    )
}

export default Button;

在控制台中,我可以看到警告:

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

如何删除此警告?我在此实施中做错了什么?我找不到任何解决方案...

1 个答案:

答案 0 :(得分:0)

实际上,React:refs的规则不会通过。那是 因为 ref 不是道具。就像map()中的 一样, 与React不同。

因此,您应该使用转发参考https://en.reactjs.org/docs/forwarding-refs.html)技术将ref传递到子组件中。 React官方文档示例:

const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>
));

// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;

在代码段中,您应该执行以下操作:

const StyledButton = React.forwardRef((props, ref }
) {
  type CombinedProps = Props & SimpleProps<T>;
  const Forwarded = styled(React.forwardRef<HTMLButtonElement, CombinedProps>(
    ({ children, isCircled, ...rest }, ref) => (
      <MuiButton ref={ref} {...rest}>
                {children}
            </MuiButton>
    )
    ))`
        background-color: green!important;
        border-radius: ${(props) => props.isCircled ? '25px' : '10px'}!important;
    `;
    return <Forwarded {...props} />
});