reactjs - Material-UI Button 组件如何推断传递给 `component` prop 的组件的 props?

标签 reactjs typescript material-ui next.js

谁能解释一下 Material-UI 如何扩展其 Button 的 Prop 如果我在 component 中传递特定组件,则使用我的组件的 Prop 的组件支柱?

interface MyLinkProps extends ButtonBaseProps {
  someRandomProp: string
}

const MyLink: React.FC<MyLinkProps> = () => {
  return <div></div>
}

<Button component={MyLink} someRandomProp="random">Something</Button>
在这种情况下,Button组件现在知道 someRandomProp属于我的组件的 Prop ;正在传递给 component Button 上的 Prop 成分。
我想达到同样的效果。我有一个 Image 组件,它有一个 Prop component我想推断正在传递的组件的 Prop 。
例如,如果有类似的东西:
<MyImage component={NextImage} {...propsOfNextImage} />
基本上,我想要MyImage自动检测和扩展 NextImage 的 Prop .

最佳答案

可以看到OverridableComponent的类型定义here ,这个负责合并overridable component的 Prop 与组件的原始 Prop 。
作为引用,请参阅如何在 MUI 组件中使用它 here .第一个泛型类型参数是具有以下属性的类型:

  • props :你的组件在与可覆盖组件的 props 合并之前的原始 props。
  • defaultComponent :如果您不提供任何组件,则为默认根组件。

  • import { OverridableComponent } from '@mui/material/OverridableComponent';
    
    interface MyImageProps {
      src: string;
      myCustomProps?: string;
    }
    interface MyImageTypeMap {
      props: MyImageProps;
      defaultComponent: 'img';
    }
    
    const MyImage: OverridableComponent<MyImageTypeMap> = (props) => {
      const RootComponent = props.component || 'img';
      return (
        <RootComponent src={props.src} {...props}>
          {props.children}
        </RootComponent>
      );
    };
    
    用法
    {/* normal component with MyImageProps. The root component is an img element */}
    <MyImage src={src} />
    {/* component with MyImageProps & ButtonProps. The root component is a Button*/}
    <MyImage src={src} component={Button} variant="contained">
      I am actually a button in disguise
    </MyImage>
    
    现场演示
    Codesandbox Demo

    关于reactjs - Material-UI Button 组件如何推断传递给 `component` prop 的组件的 props?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69482751/

    相关文章:

    javascript - 在 Redux/React 组件中改变 props 值的正确方法是什么?

    reactjs - webpack 配置加载 sass 变量无需 import 语句

    javascript - <strong>、<cite>、<article> 等的 HTMLElement 类型

    javascript - Material-UI React 无法识别 DOM 元素上的 `underlineStyle` 属性

    javascript - 有没有办法控制弹出器中嵌套的 Material UI 选择在 DOM 中的安装位置?

    reactjs - 如何将所有路由重定向到 gatsby 索引

    node.js - 部署 create-react-app - 静态还是动态?

    javascript - 如何正确键入将多个对象合并在一起的动态递归函数?

    TypeScript:具有可选值的可区分联合

    reactjs - 无法使该消息 Hook 在 React 中工作