什么是组件的重用性?html
咱们把一个大的功能拆分为一个一个的小模块,好比按钮、表单、下拉框、轮播图等。react
提升组件的重用性有什么好处呢?函数
1. 写更少的代码。this
2. 减小开发时间。spa
3. 代码的bug更少。code
4. 占用的字节更少。component
为了保证数据的正确性,咱们能够对props的数据进行验证,验证方法以下:htm
React.createClass({
propTypes:{
optionArray : React.PropTypes.array
}
})
React 容许你为组件设置默认的props:blog
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}>