我正在尝试为 React 组件的可选道具指定默认值。
我可以做到这一点,而且我可以正确获取可选属性“y”的值。
interface CompProps {
x: number;
y?: number;
}
const compPropsDefault: CompProps = {
x: 100,
y: 200
}
function CompA({ x, y = compPropsDefault.y }: CompProps = compPropsDefault) {
const props = {x, y};
console.log(props);
}
CompA({ x: 100 })
// Outputs: {"x": 100, "y": 200}
但我需要一直做
{ x, y = compPropsDefault.y }
类的解构,这对于较大的对象会变得很麻烦。另外,理想情况下,我想将所有输入道具保存在一个props
对象中。
这有效,但我找不到任何推荐这个的文档/示例。这样做会是不好的做法吗?还是有更好的方法来获得想要的结果?
function CompB(props: CompProps = compPropsDefault) {
props = { ...props, ...compPropsDefault };
console.log(props);
}
那是重新分配,而不是覆盖。重新分配几乎总是 React 中的反模式,它遵循函数式风格的原则和哲学。
默认道具对象
interface CompProps {
x: number;
y?: number;
}
const defaultProps: CompProps = {
// x: 100 // you will never see this because CompA requires `x`
y: 200
}
function CompA(props: CompProps) {
const { x, y } = {...defaultProps, ...props} //
return [ x, y ]
}
CompA({ x: 100 })
// ✅ [ 100, 200 ]
CompA({ x: 300, y: 600 })
// ✅ [ 300, 600 ]
CompA({ y: 999 })
// ✅ Error: Property "x" is missing
解构的默认值
interface CompProps {
x: number;
y?: number;
}
function CompA({ x, y = 5 }: CompProps) {
return [ x, y ]
}
CompA({ x: 100 })
// ✅ [ 100, 200 ]
CompA({ x: 300, y: 600 })
// ✅ [ 300, 600 ]
CompA({ y: 999 })
// ✅ Error: Property "x" is missing
您为 React 组件中的
optional props
设置默认值而编写的两种方法都是有效的。这仅取决于您喜欢哪种方法。
在您的第一个实现中,您使用解构从
prop value
中获取可选的 default object
。如果有很多 optional props
并且您必须多次重复此过程,这可能会很困难。
在第二种方法中,您将默认的
props object
添加为函数参数,然后使用default props
将所有道具与spread operator
合并。此解决方案允许您将所有输入保留在一个object
中,但不允许您轻松覆盖“y”的默认值,因为它总是被默认道具对象中的值覆盖。
两种方法都是正确的,各有优缺点