我如何使React组件具有以下功能:a)允许prop作为可选组件,b)在组件中一次将其视为非null?
例如我有这个简单的组件:
import React from 'react';
type props = {
x?: number;
};
const defaultProps: props = {
x: 0,
};
export default function Foo({ x }: props) {
x++;
}
Foo.defaultProps = defaultProps;
如何使该组件中的x
是不可为空的类型,以便可以干净地编写x++
?
答案 0 :(得分:0)
我可以提出以下解决方案。
interface IProps {
x?: number;
z?: string;
}
const Foo: React.FC<IProps> = ({x = 0, ...rest}) => {
x++;
const {z, children} = rest;
// Do whatever you need to do with the props, e.g.
return<div>
X prop: {x}
Z prop: {z}
Children: {children}
</div>;
};
/// Example how to use `Foo`
class ExampleClassA extends React.Component {
public render() {
return <>
<Foo/>
<Foo x={2}/>
<Foo x={2} z={"Z value"}>
Children here
</Foo>
</>
}
}