简体   繁体   English

基于多个 Typescript 接口的 React prop 分离

[英]React prop separation based on multiple Typescript interfaces

Is there a way in React to separate the props object based on an Typescript interface which extends multiple other interfaces? React 中是否有一种方法可以基于扩展多个其他接口的 Typescript 接口来分离 props 对象? The other way I see, is to pass duplicate props to components that won't use them which is not the optimal solution.我看到的另一种方式是将重复的道具传递给不会使用它们的组件,这不是最佳解决方案。

interface IProps extends IAProps, IBProps {}

const Component1: SFC<IProps> = (props) => 
   return (
     <Component2
         {...props} <--- only IAProps
     />
     <Component3
         {...props} <--- only IBProps
     />
  );
}

You can use the & to merge interfaces.您可以使用&来合并接口。 Such as <ScreenProps extends {} & SliderProps & ReactNavigationProps>比如<ScreenProps extends {} & SliderProps & ReactNavigationProps>

Example:例子:


interface AProps {
  testa: any
}

interface BProps {
  testb: any
}


class Test extends Component<AProps & BProps> {
  // ...
}


// or


<IProps extends AProps & BProps>

class Test extends Component<IProps> {
   // ...
}


if you want your component to accept any type of props based on interfaces you can do this:如果您希望您的组件接受基于接口的任何类型的道具,您可以这样做:

const Component1: SFC<IAProps & IBProps> = (props) => 
       return (
         <Component2
             {...props} <---IAProps
         />
         <Component3
             {...props} <--- IBProps
         />
      );
    }

Note that : if not your all props are required, you can use the optional props in each interface as the following:注意:如果不是你所有的 props 都是必需的,你可以在每个界面中使用可选的 props,如下所示:

interface  IAProps {
    name: string; // required
    age?: number; //optional 

}

or if your all interface's pops should be marked as required but you still want to not use all of them in your component you can do this:或者如果您的所有界面的弹出窗口都应标记为必需,但您仍然不想在组件中使用它们,您可以这样做:

const Component1: SFC<Partial<IAProps> & Partial<IBProps>> = (props) => 
       return (
         <Component2
             {...props} <---IAProps
         />
         <Component3
             {...props} <--- IBProps
         />
      );
    }

something to mention, that Partial will mark all your interface's props as optional值得一提的是, Partial会将您所有界面的道具标记为可选

I think the simple approach of just passing two different props is a clean solution:我认为只传递两个不同道具的简单方法是一个干净的解决方案:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM