【问题标题】:React prop separation based on multiple Typescript interfaces基于多个 Typescript 接口的 React 道具分离
【发布时间】:2019-09-21 23:38:53
【问题描述】:
React 中是否有一种方法可以基于扩展多个其他接口的 Typescript 接口来分离 props 对象?我看到的另一种方法是将重复的道具传递给不会使用它们的组件,这不是最佳解决方案。
interface IProps extends IAProps, IBProps {}
const Component1: SFC<IProps> = (props) =>
return (
<Component2
{...props} <--- only IAProps
/>
<Component3
{...props} <--- only IBProps
/>
);
}
【问题讨论】:
标签:
reactjs
typescript
interface
react-props
separation-of-concerns
【解决方案1】:
我认为只传递两个不同道具的简单方法是一个干净的解决方案:
interface IProps {
a: IAProps;
b: IBProps;
}
const Component1: SFC<IProps> = (props) =>
return (
<Component2
{...props.a} <--- only IAProps
/>
<Component3
{...props.b} <--- only IBProps
/>
);
}
【解决方案2】:
如果你想让你的组件接受基于接口的任何类型的 props,你可以这样做:
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 会将您界面的所有道具标记为可选
【解决方案3】:
您可以使用& 来合并接口。如<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> {
// ...
}