在React中,有没有一种方法可以基于扩展了多个其他接口的Typescript接口来分离props对象?我看到的另一种方式是将重复的道具传递给不使用它们的组件,这不是最佳解决方案。
interface IProps extends IAProps, IBProps {}
const Component1: SFC<IProps> = (props) =>
return (
<Component2
{...props} <--- only IAProps
/>
<Component3
{...props} <--- only IBProps
/>
);
}
发布于 2019-05-03 12:23:25
您可以使用&
合并接口。例如<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> {
// ...
}
发布于 2019-05-03 12:25:24
如果你想让你的组件接受任何类型的基于接口的属性,你可以这样做:
const Component1: SFC<IAProps & IBProps> = (props) =>
return (
<Component2
{...props} <---IAProps
/>
<Component3
{...props} <--- IBProps
/>
);
}
请注意,:如果不是所有的道具都是必需的,您可以使用每个接口中的可选道具,如下所示:
interface IAProps {
name: string; // required
age?: number; //optional
}
或者,如果您的所有接口的弹出窗口都应该标记为required,但您仍然不想在组件中使用它们,您可以这样做:
const Component1: SFC<Partial<IAProps> & Partial<IBProps>> = (props) =>
return (
<Component2
{...props} <---IAProps
/>
<Component3
{...props} <--- IBProps
/>
);
}
值得一提的是,Partial
会将所有接口属性标记为可选
发布于 2020-06-02 09:24:11
我认为只传递两个不同的道具的简单方法是一个干净的解决方案:
interface IProps {
a: IAProps;
b: IBProps;
}
const Component1: SFC<IProps> = (props) =>
return (
<Component2
{...props.a} <--- only IAProps
/>
<Component3
{...props.b} <--- only IBProps
/>
);
}
https://stackoverflow.com/questions/55969554
复制相似问题