我正在尝试创建一个无状态的 React 组件,其中包含可选的道具和 Typecript 中的 defaultProps (针对 React 本机项目)。对于普通的 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" />
会像预期的那样显示“兰斯洛特爵士”,但是 <Test />
在应该输出的时候什么结果也没有
“ McGee 先生”。
非常感谢您的帮助。