React.js中的抽象

mqk*_*lin 10 javascript flux reactjs reactjs-flux

我想在创建我的React组件时使用一些抽象.例如:

class AbstractButton extends React.Component {
  render() {
    return (
      <button
        onClick={this.props.onClick}
        className={this.definitions.className}>
        {this.props.text}
      </button>
    }
}
class PrimaryButton extends AbstractButton {
  constructor(options) {
    super(options);
    this.definitions = {
        className: 'btn btn-primary'
    };
  }
}
class SuccessButton extends AbstractButton {
  constructor(options) {
    super(options);
    this.definitions = {
        className: 'btn btn-success'
    };
  }
}
Run Code Online (Sandbox Code Playgroud)

我不想通过这些definitions,props因为我知道这些definitions- 在这种情况下 - 将class永远不会改变.

它是React中的反模式吗?还是可以吗?

我的问题涉及这个altjs问题:这种抽象与之不兼容@connectToStores.

Bra*_*don 10

一般来说,没有理由不在这里使用组合而不是深度继承:

class Button extends React.Component {
  render() {
    return (<button
             onClick={this.props.onClick}
             className={this.props.className}
           >
             {this.props.text}
           </button>);
  }
  static propTypes = {
      className: React.PropTypes.string.isRequired,
      onClick: React.PropTypes.func
  }
}

class PrimaryButton extends React.Component {
  render() {
    return <Button {...this.props} className="btn btn-primary" />;
  }
}
Run Code Online (Sandbox Code Playgroud)

这与您的建议一样功能,但更简单,更容易推理.它非常清楚您Button实际需要哪些信息来完成其工作.

一旦实现这一飞跃,您可以完全消除类并使用无状态组件:

const Button = (props) => (<button
             onClick={props.onClick}
             className={props.className}
           >
             {props.text}
           </button>);
Button.propTypes = {
      className: React.PropTypes.string.isRequired,
      onClick: React.PropTypes.func
};

const PrimaryButton = (props) =>
    <Button {...props} className="btn btn-primary" />;

const SuccessButton = (props) =>
    <Button {...props} className="btn btn-success" />;
Run Code Online (Sandbox Code Playgroud)

这将允许React应用更多优化,因为您的组件不需要任何特殊的生命周期事件支持或状态管理.由于现在您只使用纯函数,因此更容易推理.

顺便说一下,如果你试图制作一些包裹Bootstrap的React组件,那么也许你应该看看React-Bootstrap.