我正在尝试在 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 许可协议
这是一个带有答案的类似问题: React with TypeScript - define defaultProps in stateless function