如何使用TypeScript为无状态的,功能齐全的React组件指定(可选)默认道具? [英] How to specify (optional) default props with TypeScript for stateless, functional React components?
问题描述
我正在尝试在Typescript中创建一个带有可选props和defaultProps的无状态React组件(对于React Native项目)。这对于vanilla JS来说是微不足道的,但我对如何在TypeScript中实现它感到困惑。
I'm trying to create a stateless React component with optional props and defaultProps in Typescript (for a React Native project). This is trivial with vanilla JS, but I'm stumped as to how to achieve it in 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;
调用<测试标题=Sirname =Lancelot/ >
按预期呈现Sir Lancelot,但< Test />
什么都没有,什么时候输出
McGee先生。
Calling <Test title="Sir" name="Lancelot" />
renders "Sir Lancelot" as expected, but <Test />
results in nothing, when it should output
"Mr McGee".
非常感谢任何帮助。
推荐答案
这是一个类似的问题和答案:与TypeScript反应 - 在无状态下定义defaultProps功能
Here's a similar question with an answer: 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;
这篇关于如何使用TypeScript为无状态的,功能齐全的React组件指定(可选)默认道具?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!