【发布时间】:2019-05-24 11:27:13
【问题描述】:
我正在构建一个组件,它要么应该接收一个名为 text 的 prop,要么接收孩子 - 既不是两者也不是。
✓ 允许
<NotificationBar text="Demo"/>
<NotificationBar>Demo</NotificationBar>
✗ 不允许
<NotificationBar/>
<NotificationBar text="Demo">Demo</NotificationBar>
来源
interface IWithChildren {
children: ReactNode;
text?: never;
}
interface IWithText {
text: JSX.Element | string;
children?: never;
}
type TNotification = (IWithChildren | IWithText);
export const NotificationBar = ({ text, children }: TNotification) => {}
TypeScript 方面它可以工作,但 React 仅在使用 text 属性时会发出警告:
<NotificationBar text="Demo"/>
元素 NotificationBar 没有必需的子属性
除此之外,它按预期工作。
我怎样才能为我的 React 组件创建一个接口,它根据给定的 props 匹配一个接口,并且不会收到警告?
【问题讨论】:
-
你可以在这里复制这个codesandbox.io/s/react-ts 吗?
-
您收到的警告是由您的 IDE 发出的?因为我只是尝试复制/粘贴您写的内容,VSCode 没有给出警告
-
我理解你的想法,但也许你应该考虑只使用儿童道具。这个 API 设计有点混乱 imo。我认为在这种情况下使用儿童道具是全球标准,而不是从我的脑海中浮现。
标签: reactjs typescript