【问题标题】:How to extend type union props to a react class component?如何将类型联合道具扩展到反应类组件?
【发布时间】:2022-01-10 18:26:07
【问题描述】:

我有两个道具showAccountNameaccountType。 仅当showAccountName 为真时,才需要accountType。当 showAccountName 为 false 时,accountType 不是必需的。

所以,我使用了类型联合 -

type AccountProps = 
| { showAccountName?: false; accountType: never; }
| { showAccountName?: true; accountType: string; }

并尝试在类组件中扩展这些道具

class UserAccount extends React.PureComponent<AccountProps> 
{ .... }

但我无法在 UserAccount 中使用 this.props 访问 showAccountName 或 accountType。知道我在这里做错了什么吗?或者有没有其他方法可以根据另一个可选道具强制使用一个道具? (不使用类型) 我是打字稿的新手,非常感谢任何帮助!

【问题讨论】:

  • “无法访问”是什么意思?您是否收到特定的错误消息?当我尝试您的代码时,它似乎工作正常:tsplay.dev/NnXxVW
  • 为什么让它们成为可选的?见this例子

标签: reactjs typescript types react-props extends


【解决方案1】:

不要在这两种情况下将showAccountName 设为可选属性,而是仅在它应该是虚假的情况下将其设为可选(并且在这种情况下也只需省略另一个属性):

{ showAccountName?: false; }

如果您希望显示它,请将两个道具设为非可选:

{ showAccountName: true; accountType: string; }

所以,加在一起,它看起来像这样:

import {default as React} from 'react';

type AccountProps = 
  | { showAccountName?: false; }
  | { showAccountName: true; accountType: string; };

class UserAccount extends React.PureComponent<AccountProps> {
  render () {
    return (
      <div>
        {this.props.showAccountName ? this.props.accountType : 'Account type not shown'}
      </div>
    );
  }
}

TS Playground

【讨论】:

    猜你喜欢
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-31
    • 2019-10-07
    相关资源
    最近更新 更多