加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – 创建基本组件然后在React中扩展它们是一个好习惯吗?

发布时间:2020-12-15 05:08:05 所属栏目:百科 来源:网络整理
导读:我刚学习React,我正在使用ES7语法编写组件. 我的想法是创建一个基本组件,它将包含一些我希望所有派生组件都具有的方法.例如,我想在所有组件中实现 valueLink without the mixin,以实现双向绑定.这是我的想法: class MyComponent extends React.Component {
我刚学习React,我正在使用ES7语法编写组件.
我的想法是创建一个基本组件,它将包含一些我希望所有派生组件都具有的方法.例如,我想在所有组件中实现 valueLink without the mixin,以实现双向绑定.这是我的想法:
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方式一样.所以我想知道这是完全没问题,还是有一些我不知道的缺陷.谢谢.

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

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

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)

我没有测试过这个,但它应该可行.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读