blog icon indicating copy to clipboard operation
blog copied to clipboard

Typing defaultProps 不推荐使用

Open nmsn opened this issue 3 years ago • 0 comments

来源:https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/default_props/

不推荐使用 defaultProps 来定义组件的默认值, 而是使用对象默认值

type GreetProps = { age?: number };

const Greet = ({ age = 21 }: GreetProps) => // etc

使用 defaultProps 会存在这样的问题:

interface IProps {
  name: string;
}

const defaultProps = {
  age: 25,
};

const GreetComponent = ({ name, age }: IProps & typeof defaultProps) => (
  <div>{`Hello, my name is ${name}, ${age}`}</div>
);

GreetComponent.defaultProps = defaultProps;

const TestComponent = (props: React.ComponentProps<typeof GreetComponent>) => {
  return <h1 />;
};

// Property 'age' is missing in type '{ name: string; }' but required in type '{ age: number; }'
const el = <TestComponent name="foo" />;

另外使用 eslint 的 react/require-default-props 规则也会有问题

const Person = ({ name, age = 18 }: { name: string; age?: number }) => {
  return (
    <div>
      <span>{name}</span>
      <span>{age}</span>
    </div>
  );
};

// propType "age" is not required, but has no corresponding defaultProps declaration.eslint[react/require-default-props](https://github.com/yannickcr/eslint-plugin-react/tree/master/docs/rules/require-default-props.md)

建议关闭这条 eslint rule

nmsn avatar Jul 09 '22 06:07 nmsn