gpt4 book ai didi

javascript - 如何使用 TypeScript 为无状态、功能性 React 组件指定(可选)默认 Prop ?

转载 作者:可可西里 更新时间:2023-11-01 01:47:08 25 4
gpt4 key购买 nike

我正在尝试在 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" />按预期呈现“兰斯洛特爵士”,但 <Test />结果什么都没有,什么时候应该输出“麦吉先生”。

非常感谢任何帮助。

最佳答案

这是一个带答案的类似问题: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;

关于javascript - 如何使用 TypeScript 为无状态、功能性 React 组件指定(可选)默认 Prop ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40209352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com