我正在尝试在 Typescript 中创建一个带有可选 props 和 defaultProps 的无状态 React 组件(对于 React Native 项目)。这对于普通 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;
Calling <Test title="Sir" name="Lancelot" />
按预期呈现“兰斯洛特爵士”,但是<Test />
当它应该输出时什么结果也没有
“麦吉先生”。
任何帮助是极大的赞赏。
这是一个类似的问题及其答案:React with TypeScript - 在无状态函数中定义 defaultProps https://stackoverflow.com/questions/37262047/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;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)