[英]React prop separation based on multiple Typescript interfaces
React 中是否有一种方法可以基于扩展多个其他接口的 Typescript 接口来分离 props 对象? 我看到的另一种方式是将重复的道具传递给不会使用它们的组件,这不是最佳解决方案。
interface IProps extends IAProps, IBProps {}
const Component1: SFC<IProps> = (props) =>
return (
<Component2
{...props} <--- only IAProps
/>
<Component3
{...props} <--- only IBProps
/>
);
}
您可以使用&
来合并接口。 比如<ScreenProps extends {} & SliderProps & ReactNavigationProps>
例子:
interface AProps {
testa: any
}
interface BProps {
testb: any
}
class Test extends Component<AProps & BProps> {
// ...
}
// or
<IProps extends AProps & BProps>
class Test extends Component<IProps> {
// ...
}
如果您希望您的组件接受基于接口的任何类型的道具,您可以这样做:
const Component1: SFC<IAProps & IBProps> = (props) =>
return (
<Component2
{...props} <---IAProps
/>
<Component3
{...props} <--- IBProps
/>
);
}
注意:如果不是你所有的 props 都是必需的,你可以在每个界面中使用可选的 props,如下所示:
interface IAProps {
name: string; // required
age?: number; //optional
}
或者如果您的所有界面的弹出窗口都应标记为必需,但您仍然不想在组件中使用它们,您可以这样做:
const Component1: SFC<Partial<IAProps> & Partial<IBProps>> = (props) =>
return (
<Component2
{...props} <---IAProps
/>
<Component3
{...props} <--- IBProps
/>
);
}
值得一提的是, Partial
会将您所有界面的道具标记为可选
我认为只传递两个不同道具的简单方法是一个干净的解决方案:
interface IProps {
a: IAProps;
b: IBProps;
}
const Component1: SFC<IProps> = (props) =>
return (
<Component2
{...props.a} <--- only IAProps
/>
<Component3
{...props.b} <--- only IBProps
/>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.