如何使用 TypeScript 为无状态的功能性 React 组件指定(可选)默认道具?

新手上路,请多包涵

我正在尝试在 Typescript 中创建一个带有可选 props 和 defaultProps 的无状态 React 组件(用于 React Native 项目)。这对于 vanilla JS 来说是微不足道的,但我对如何在 TypeScript 中实现它感到困惑。

使用以下代码:

 import React, { Component } from 'react';
import { Text } from 'react-native';

interface TestProps {
    title?: string,
    name?: string
}

const defaultProps: TestProps = {
    title: 'Mr',
    name: 'McGee'
}

const Test = (props = defaultProps) => (
    <Text>
        {props.title} {props.name}
    </Text>
);

export default Test;

调用 <Test title="Sir" name="Lancelot" /> 会按预期呈现“Sir Lancelot”,但 <Test /> 应该输出“Mr McGee”时没有任何结果。

任何帮助是极大的赞赏。

原文由 Matt Stow 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 554
2 个回答

这是一个带有答案的类似问题: React with TypeScript - define defaultProps in stateless function

 import React, { Component } from 'react';
import { Text } from 'react-native';

interface TestProps {
    title?: string,
    name?: string
}

const defaultProps: TestProps = {
    title: 'Mr',
    name: 'McGee'
}

const Test: React.SFC<TestProps> = (props) => (
    <Text>
        {props.title} {props.name}
    </Text>
);

Test.defaultProps = defaultProps;

export default Test;

原文由 Matt Stow 发布,翻译遵循 CC BY-SA 3.0 许可协议

2022 年更新

对于功能组件,确实有 可能弃用 defaultProps 字段。我不相信这会很快发生,因为已经用它编写了大量的代码,但是很可能会在控制台中显示警告。

我正在使用下面的解决方案,它提供了正确的行为和正确的 TypeScript 验证。它适用于混合定义/未定义的属性,也适用于有/没有默认值的属性——也就是说,它涵盖了所有情况:

 interface Props {
  name: string;
  surname?: string;
  age?: number;
}

const defaultProps = {
  surname: 'Doe',
};

function MyComponent(propsIn: Props) {
  const props = {...defaultProps, ...propsIn};

  return <div>{props.surname}</div>;
}

VSCode 自动完成功能在:

VSCode 自动完成

它已经使用 TypeScript 4.7 进行了测试。

原文由 rodrigocfd 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题