简体   繁体   English

扩展 Material-UI 组件是否正确(React / Typescript)

[英]Is it a correct way to extend Material-UI components (React / Typescript)

I'm trying to extend material-ui components as my own component with custom properties.我正在尝试将 material-ui 组件扩展为我自己的具有自定义属性的组件。 I'm using reactjs w/ typescript.我正在使用带有 typescript 的 reactjs。

The below code is my trial:以下代码是我的试用版:

import React from 'react';
import clsx from 'clsx';
import { makeStyles } from '@material-ui/core';
import { Theme } from '@material-ui/core/styles/createMuiTheme';
import Tabs, { TabsProps } from '@material-ui/core/Tabs';

export interface Iprops extends TabsProps {
  /* how to add a variant ? */
}

const useStyles = makeStyles((theme: Theme) => ({
    root: {
       // styles
     }
}));

export const BasicTabs = (props: Iprops) => {
    const classes = useStyles(props);
    if (props.variant === 'test') {
        return (
            <Tabs
                {...props}
                className={clsx(classes.root, props.className)}
            />
        );
    }
    return (
        <Tabs {...props} />
    );
};

So, what Im trying to do now is return a custom styled button when the variant is 'test'.所以,我现在要做的是在变体为“测试”时返回一个自定义样式的按钮。

So, my first question is所以,我的第一个问题是
1. How to add a new variant to the button? 1.如何为按钮添加新的变体?

the second question is第二个问题是
2. should I pass the children like 2.我应该通过孩子喜欢

<Tabs {...props}>{props.children}</Tabs>

all the time whenever I extend a material-ui components?每当我扩展 material-ui 组件时,我一直都在吗?

import React from 'react'
import TextField, { StandardTextFieldProps } from '@material-ui/core/TextField'

/**
 * Extend properties
 */
export interface PasswordProps extends StandardTextFieldProps {
    custom: string
}

/**
 * Password input
 * @param props Properties
 */
export const PasswordField: React.FunctionComponent<PasswordProps> = (props) => {
    props = Object.assign({ type: 'password' }, props)
    return (
        <TextField {...props}>
            {props.children}
        </TextField>
    )
}

For your questions: A. Extend the props, add variants to the interface you want.对于您的问题: A. 扩展道具,为您想要的界面添加变体。 B. Yes, always like this as suggested with React official 'composition model' https://reactjs.org/docs/composition-vs-inheritance.html B. 是的,总是像 React 官方“组合模型”所建议的那样 https://reactjs.org/docs/composition-vs-inheritance.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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