我有一个 TSX 组件,它是一个像这样包装其子组件的容器:
import * as React from "react";
interface IProps extends React.Props<Box> {
}
interface IState {
}
export class Box extends React.Component<IProps, IState> {
render() {
return (
<div>
<h3>Check this out:</h3>
{this.props.children}
</div>);
}
}
我也有一些纯组件,比如这个:
// ReSharper disable once InconsistentNaming - React components must start with a capital letter.
export function LabelTest(props: { label: string }) {
return (
<div style={{ display: "flex" }}>
<label style={{ flex: "1 0 0" }}>{props.label}</label>
<div style={{ width: "auto" }}>
This is a pure component.
</div>
</div>);
}
不过,我这辈子都想不出如何制作纯容器组件。声明看起来没问题,没有显示错误:
// ReSharper disable once InconsistentNaming - React components must start with a capital letter.
export function LabelBox(props: { label: string, children: React.ReactNode }) {
return (
<div style={{ display: "flex" }}>
<label style={{ flex: "1 0 0" }}>{props.label}</label>
<div style={{ width: "auto" }}>
{props.children}
</div>
</div>);
}
children
是React.ReactNode
因为这就是 React.Props<X>
中的内容.
使用时,我得到 TS2324 属性“children”在类型“IntrinsicAttributes & { label: string; 中丢失” children :ReactElement |字符串 |编号 | {} | ( react ...。
// ReSharper disable once InconsistentNaming - React components must start with a capital letter.
export function LabelNumberInput(props: { label: string, value: number }) {
return (
<LabelBox label={props.label}>
<input type="number" value={props.value} />
</LabelBox>);
}
我不能说下面的代码片段,因为它会说无法在外部模块 _.tsx 中找到符号“LabelBox”(这是所有这些代码所在的文件)。功能先放还是接口(interface)先放都无所谓,反正总感觉不对。
interface ILabelBoxProps extends React.Props<LabelBox> { label: string }
export function LabelBox(props: ILabelBoxProps) {
return (
<div style={{ display: "flex" }}>
<label style={{ flex: "1 0 0" }}>{props.label}</label>
<div style={{ width: "auto" }}>
{props.children}
</div>
</div>);
}
使纯 TypeScript React 组件能够像完整类组件一样接收子组件的正确方法是什么?这可能吗?我认为不应该,它仍然是一个无状态组件并且 children
只是一种特殊的 props
,真正的问题似乎是这里的工具 (Visual Studio) 没有将 TSX 内容节点映射到 children
Prop 。
最佳答案
What's the right way to make a pure TypeScript React component capable of taking children just like a full class component would
示例🌹:
interface PrimitiveProps extends React.HTMLProps<HTMLDivElement>{
myAdditionalProp:any;
};
export const Content = (allProps: PrimitiveProps) => {
const {myAdditionalProp, ...props} = allProps;
return (
<div data-comment="Content" {...props}/>;
);
};
当然,您可以自由地使用 myAdditionalProp
做任何事情,如果您愿意,可以将更多 Prop 放入 PrimitiveProps
中。在传递之前,请务必将它们从 allProps
中删除。请注意,children
作为 allProps
的一部分传递,因此 props
。
关于带有子项的 ReactJS TypeScript 纯组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37822233/