组件创建
React组件的创建
React.Component
使用es6的class类来继承React的组件类, 构造函数可以省略,如下是默认的写法。要是写了构造函数,要使用this获取上下文环境,必须使用超类重写构造函数,也就是调用 super(); 参数props 写了就可以在构造函数里使用组件的props 属性。原文链接:https://segmentfault.com/a/1190000008165717
import React {Component} from 'react' ; // Component = React.Component
import {render} from "react-dom" ; // render =ReactDom.render
class MainCom extends Component {
constructor(props){
super(props);
}
render(){
return (
<div>
<p>es6组件</p>
</div>
)
}
}
render(<MainCom/> ,document.getElementById("app"));
function
使用无状态的函数组件,不能设置组件状态,也就是不能使用 state 属性,可以当做只是用来展示html标签,也叫纯组件。优点和纯函数类似,复用度高,可以任意和别的组件组合
由于被简化成一个render方法的函数,所以不会被实例化,于是没有内存的分配,减少内存的开销。
不会被实例化,无法访问React组件的this中的对象,this.ref , this.props ,this.state都不行
不需要组件的生命周期,所以底层实现这种组件时没有实现生命周期的方法。
无状态组件只能访问输入的props,同样的props会得到同样的渲染结果,不会有副作用,是纯函数。
function FunCom(props){
return (<div>
<p>无状态组件 {props.name}</p>
</div>
)
}
ReactDom.render(<FunCom name="无状态"/> ,document.getElementById("app"));
React.createClass
es5的创建方式 React.createClass(),已经快被废弃,
会自绑定函数,不如es6的Component只绑定需要关心的函数。导致不必要的性能开销和代码过时的可能性
createClass的mixins不够自然直观。Component更适合高阶组件(HOC),并且使用的是纯净的js,不会被废弃。
var Hellow = React.createClass({
propType:{//属性设置
name:"test"
},
defaultProps:{//组件默认的props对象
name:"test"
},
getInitialState:function(){
return {
text:this.props.name
}
},
handleChange:function(event){
this.setState({
text:event.target.value
})
},
render:function(){
return (
<div>
Type something
<input onChnage= {this.handleChange} valeu={this.state.name} />
</div>
)
}
Hellow .propTypes = {
initialValue: React.PropTypes.string
};
Hellow .defaultProps = {
initialValue: ''
};
})
用createClass 创建的方式快要被抛弃,官方建议尽量使用无状态的组件,否则使用es6的class继承模式。
Last updated
Was this helpful?