【问题标题】:What's the correct way to do inheritance in TypeScript for React components?在 TypeScript 中为 React 组件进行继承的正确方法是什么?
【发布时间】:2017-06-05 22:15:40
【问题描述】:

举个例子:

export interface IBaseIconProperties {
    path: string;
}

export default class BaseIcon extends React.Component<IBaseIconProperties, any> {
    public render() {
        return (
            <SvgIcon style={{width: 32, height: 32}}>
                <path d={this.props.path} />
            </SvgIcon>
        );
    }
}

export default class Foo extends React.Component<any, any> {
    public render() {
        return <BaseIcon path="/* SVG path for Foo button goes here... */"/>;
    }
}

export default class Bar extends React.Component<any, any> {
    public render() {
        return <BaseIcon path="/* SVG path for Bar button goes here... */"/>;
    }
}

这是使用 React 组件进行继承的一种方式。不确定是否可以调用此继承。

但是还有其他方法吗?更好的方法?也许通过BaseIcon 类是abstract 的实际继承?这是否可以在不使事情过于复杂的情况下以某种方式实现?

【问题讨论】:

    标签: reactjs inheritance typescript components


    【解决方案1】:

    创建基类abstract 并从子类扩展它并没有错。以下是您可以为您提供的示例执行的操作:

    export interface IBaseIconProperties {
            path: string;
        }
    
    export default abstract class BaseIcon extends React.Component<IBaseIconProperties, any> {
            public baseRender(path:String) {
                return (
                    <SvgIcon style={{width: 32, height: 32}}>
                        <path d={path} />
                    </SvgIcon>
                );
            }
    
            //put other useful base class methods here
        }
    
    export default Foo extends BaseIcon {
        public render() {
           return this.baseRender("FooPath");
        }
    }
    
    export default Bar extends BaseIcon {
        constructor(props: IBaseIconProperties) {
          super(props);
          this.state = {
              //initialize state here, respecting the state type of the base class
          };
        }
    
        public render() {
           return this.baseRender("BarPath");
        }
    }
    

    我们在项目中做了一些非常相似的事情,而且效果很好(不过我们只有简单的案例)。

    缺点是您不能轻松地为子类声明不同的状态和属性类型,这可能是一个限制。

    【讨论】:

    • Aaaahh... 来自 Java 的我一直试图打电话给 super.render(),但没有成功。我想诀窍在于baseRender 函数。谢谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2011-03-13
    • 2016-11-21
    • 2021-02-21
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    相关资源
    最近更新 更多