2017-01-20 18 views
1

は、次の例を見てみましょう:TypeScript for Reactコンポーネントの継承を行う正しい方法は何ですか?

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... */"/>; 
    } 
} 

これは、1つのコンポーネントに反応して継承を行うことができます1つの方法です。しかし、この継承を呼び出すことができるかどうかは分かりません。

しかし、別の方法がありますか?より良い方法ですか?たぶんBaseIconクラスがabstractの実際の継承を通してですか?それは何とか複雑な事を複雑にせずに可能ですか?

答えて

2

基本クラス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"); 
    } 
} 

(我々は唯一しかし、単純な例を持っている)私たちは、私たちのプロジェクトに非常によく似た何かをすると、それは非常によく働いています。

制限がある可能性があるため、サブクラスのさまざまな状態とプロパティの種類を簡単に宣言できないという欠点があります。

+0

Aaaahh ... Javaから来て、私はいつも 'super.render()'を呼び出そうとしていて、うまくいきませんでした。トリックは 'baseRender'関数上にあると思います。ありがとう:) –

関連する問題