我有两个道具showAccountName和accountType。只有当accountType为真时才需要showAccountName。如果showAccountName为false,则不需要accountType。
所以,我用了一种类型的结合-
type AccountProps =
| { showAccountName?: false; accountType: never; }
| { showAccountName?: true; accountType: string; }并试图在类组件中扩展这些道具。
class UserAccount extends React.PureComponent<AccountProps>
{ .... }但是,我无法使用showAccountName或accountType访问UserAccount中的this.props。你知道我在这里做错什么了吗?或者有没有其他方法可以使一个道具在另一个可选道具的基础上强制执行?(不使用打字)我是新手,任何帮助都是非常感谢的!
发布于 2022-01-10 22:55:40
与其在这两种情况下都将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>
);
}
}https://stackoverflow.com/questions/70657236
复制相似问题