码迷,mamicode.com
首页 > 其他好文 > 详细

组件的重用性

时间:2017-02-21 01:01:31      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:语法   es6   function   react   bug   already   规则   array   bsp   

什么是组件的重用性?

我们把一个大的功能拆分为一个一个的小模块,比如按钮、表单、下拉框、轮播图等。

提高组件的重用性有什么好处呢?

1. 写更少的代码。

2. 减少开发时间。

3. 代码的bug更少。

4. 占用的字节更少。

 

为了保证数据的正确性,我们可以对props的数据进行验证,验证方法如下:

React.createClass({
    propTypes:{
        optionArray : React.PropTypes.array
    }
})

 

React 允许你为组件设置默认的props:

var componentDefaultProps = React.createClass({
    getDefaultProps : function(){
        return{
            value : "default value"
        }
    }
})

 

当然,props也是可以重其他地方传入的:

class HelloMessage extends React.Component {
  render() {
    return <div>Hello {this.props.name}</div>;
  }
}
ReactDOM.render(<HelloMessage name="Sebastian" />, mountNode);

 

PropTypes 和 defaultProps有什么区别呢?

  PropTypes只定义props中对应的值的类型,验证规则。

  defaultProps是设置props中默认的值。

export class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {count: props.initialCount};
    this.tick = this.tick.bind(this);
  }
  tick() {
    this.setState({count: this.state.count + 1});
  }
  render() {
    return (
      <div onClick={this.tick}>
        Clicks: {this.state.count}
      </div>
    );
  }
}
Counter.propTypes = { initialCount: React.PropTypes.number };
Counter.defaultProps = { initialCount: 0 };



// 用ES6的写法如下
const HelloMessage = (props) => <div>Hello, {props.name}</div>;
HelloMessage.propTypes = { name: React.PropTypes.string }
HelloMessage.defaultProps = { name: ‘John Doe‘ }
ReactDOM.render(<HelloMessage name="M?d?lina"/>, mountNode);

 

它的语法和ES6的一样,所以它不会自动绑定this,可以显示的使用bind(this) 或者 使用箭头函数来进行绑定。

绑定的方式有很多,但最方便,最好的绑定方式是在构造器constructor中绑定,在此绑定一次,其他地方都可以使用了。

constructor(props) {
  super(props);
  this.state = {count: props.initialCount};
  this.tick = this.tick.bind(this);
}

// It is already bound in the constructor
<div onClick={this.tick}>

 

 

 

 

参考地址:http://reactjs.cn/react/docs/reusable-components.html

 

组件的重用性

标签:语法   es6   function   react   bug   already   规则   array   bsp   

原文地址:http://www.cnblogs.com/xiangming25/p/6422123.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!