12

我只是在学习 React,我正在使用 ES7 语法编写组件。我的想法是创建一个基础组件,其中将包含一些我希望所有派生组件都具有的方法。例如,我想在没有 mixin 的情况下实现 valueLink,以便在我的所有组件中进行双向绑定。这是我的想法:

class MyComponent extends React.Component {

    bindTwoWay(name) {
        return {
            value: this.state[name],
            requestChange: (value) => {
                this.setState({[name]: value})
            }
        }
    };
}

 

class TextBox extends MyComponent {
    state = {
        val: ''
    };

    render() {
        return (<div>
            <input valueLink={this.bindTwoWay('val')}/>
            <div>You typed: {this.state.val}</div>
        </div>)
    }
}

它工作得很好。但是,我无法找到有关此方法的太多信息。这与 valueLink 无关,这只是一个例子。这个想法是在基础组件中包含一些方法,然后扩展该组件,以便派生组件具有所有这些方法,就像通常的 OOP 方式一样。所以我只想知道这是否完全没问题,或者有一些我不知道的缺陷。谢谢。

4

2 回答 2

7

这完全没问题,它只是基本的继承。使用继承来替换 mixins 的警告是没有多重继承,所以你不能像你给它多个 mixins 一样给你的 TextBox 提供多个基类的特性。要解决这个问题,您可以使用组件组合。在您的情况下,组合不会像您在示例中定义的那样直接工作,但有一个解决方法。

首先,您需要定义一个组成组件

export default (ComposedComponent) => {
  class MyComponent extends React.Component {
    constructor(props, state) {
      super(props, state);
      this.state = {
        val: ''
      };
    }
    bindTwoWay(name) {
      return {
        value: this.state[name],
        requestChange: (value) => {
            this.setState({[name]: value})
        }
      };
    }

    render() {
      return (
        <ComposedComponent 
          {...this.props}
          {...this.state} 
          bindTwoWay={this.bindTwoWay.bind(this)}
        />
      }
    }
  }

  return MyComponent
}

然后在需要一些通用功能的地方定义组件

import compose from 'path-to-composer';

class TextBox extends React.Component {
  render() {
    return (
      <div>
        <input valueLink={this.props.bindTwoWay('val')}/>
        <div>You typed: {this.props.val}</div>
      </div>
    )
  }
}

export default compose(TextBox)

我没有对此进行测试,但它应该可以工作。

于 2016-02-09T21:18:22.867 回答
4

我不建议创建您自己的基础组件并从中驱动,而是使用 react 文档中建议的组合。 https://reactjs.org/docs/react-component.html#overview在此处输入图像描述

于 2020-08-01T08:47:17.823 回答