小编典典

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

reactjs

我正在尝试在Typescript中创建一个带有可选道具和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;

调用<Test title="Sir" name="Lancelot" />将按预期方式呈现“ Sir Lancelot”,但<Test />在应输出“ McGee先生”时没有任何结果。

任何帮助是极大的赞赏。


阅读 315

收藏
2020-07-22

共1个答案

小编典典

这是一个带有答案的类似问题:使用TypeScript进行反应-在无状态函数中定义defaultProps

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;
2020-07-22