React and ES6 inheritance

我们两清 提交于 2019-12-03 13:39:49

There is a great post about writing ReactJS in ES6.

http://ilikekillnerds.com/2015/02/developing-react-js-components-using-es6/

Anyway when using ES6 you don't use React.createClass. you just create class that extends React.Component

Also in ES6 you don't have getInitialState not defaultProps. it's replaced in favor using this.state inside constructor.

Check out this example. Let's say you have Card component and Welcome Panel that extends Card component.

The code is as following:

Card Component:

import React , { Component } from 'react'
class Card extends Component {
  constructor(props){
    super(props);
  }

  render() {
    return (
      <div className="card">
           <div className="card__content">
             <label>{this.props.content}</label>
           </div>
      </div>
      )
  }

  initPanel(el,content){
    React.render( <Card content={content} />, el);   
  }
}

export default Card;

Welcome Panel Component:

import React from 'react';
import Card from 'components/card.component';

class WelcomePanel extends Card {
  constructor(props){
    super(props);
    this.state = {
      content: "Welcome Panel",
      index: 0
    }
  }

  componentClicked(){
    this.setState({content: "Component Clicked", index: this.state.index + 1})
  }

  render() {
    return (
      <div className="welcome-panel" onClick={this.componentClicked.bind(this)}>
         <Card content={`${this.state.content} ${this.state.index > 0 ? this.state.index  : ''} ${this.state.index > 0 ? 'times' : ''} `} />
      </div>
      )
  }

  initPanel(el,content){
    React.render( <WelcomePanel />, el);   
  }
}

export default { Class: WelcomePanel }

Here is the workaround I've found :

Inside React.js library, I've updated the ReactCompositeComponentInterface to add a custom policy for constructor (As far as I know there's no way to customize this 'interface' properly) :

var ReactCompositeComponentInterface = {

/**
 * An array of Mixin objects to include when defining your component.
 *
 * @type {array}
 * @optional
 */
mixins: SpecPolicy.DEFINE_MANY,

/**
 * Custom policy for 'constructor'
 */
constructor: SpecPolicy.DEFINE_MANY,

  ...

}

Then in the ExtendedClass, you have to redefine every method even if you don't customize them :

class ExtendedClass extends BaseClass{
    getInitialState(){
        return {message: "Hello! I'm an extension"};
    }
    /** required */
    render(){
        return super.render();
    }
}

I'm not happy with this dirty solution but it will do the job waiting for a 0.13 version that hopefully will solve those issues.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!