【问题标题】:Spreading a component's props across two different child components in React在 React 中将组件的 props 分布在两个不同的子组件中
【发布时间】:2020-11-06 13:51:39
【问题描述】:

我正在尝试创建一个自定义电子邮件输入组件(用于表单),它将 Material-UI TextField 组件包装在我制作的自定义网格组件中。理想情况下,我希望能够将我想要的任何 TextField 道具传递到该组件中,并通过传播道具将其应用于内部 TextField 组件,但我也希望能够为自定义网格组件传递任何道具和也可以通过传播将它们应用于网格组件。

示例(variant 是 TextField 属性,width 是 CustomGrid 属性):

// CustomEmailField.tsx

...

export const CustomEmailField: React.FC<TextFieldProps & CustomGridProps> = (props) => {
   return(
       <CustomGrid {...props as CustomGridProps}>
            <TextField {...props as TextFieldProps} />
       </CustomGrid>
   );
};
// index.tsx

...

const App = () => {
   return(
      <>
         <h1>Enter your email</h1>
         <CustomEmailField variant={'outlined'} width={2} />
      </>
   );
};

但是,当传播网格组件的道具时,我收到一条错误消息,指出此网格组件不存在 TextField 道具(本示例中的变体),同样,网格组件的道具(本示例中的宽度) 对于 TextField 组件不存在。

什么是解决此问题的好方法,以便我仍然可以灵活地传递给每个(子)组件的道具,而不必硬编码电子邮件(父)组件可以接受哪些道具?

【问题讨论】:

    标签: reactjs material-ui react-props destructuring


    【解决方案1】:

    只需创建一个新的道具类型。

    export type CustomEmailFieldProps = {
       textField: TextFieldProps;
       customGrid: CustomGridProps;
    }
    
    export const CustomEmailField: React.FC<CustomEmailFieldProps> = ({textField, customGrid}) => {
       return(
           <CustomGrid {...customGrid}>
                <TextField {...textField} />
           </CustomGrid>
       );
    };
    

    要使用,只需创建一个你想要传递给每个道具的对象。

    // index.tsx
    
    ...
    
    const App = () => {
       return(
          <>
             <h1>Enter your email</h1>
             <CustomEmailField textField={{variant: 'outlined'}} customGrid={{width: 2}} />
          </>
       );
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-28
      • 2018-07-31
      • 2022-01-03
      • 1970-01-01
      相关资源
      最近更新 更多