一、react写法
`React.createClass`是react刚开始推荐的创建组件的方式,这是ES5的原生的JavaScript来实现的React组件,其形式如下:
import React,{PropTypes} from 'react'
import ReactDom from ;react-dom;
var SayHi = React.createClass({
getInittialState(){
return {}
},
getDefaultProps(){
return {}
},
propTypes:{
},
render(){
var name = this.props.name;
return (
{from} says:hello {name};
)
}
})
ReactDOM.render(,document.getElementById('demo'))
二、ES6写法 React.Component
import React, { Component, PropTypes } from 'react';
import { Popover, Icon } from 'antd';
class InputControlES6 extends React.Component{
constructor(pros){//初始化的工作放入到构造函数
super(pros);
this.state = {//初始state设置方式
visible:false,
text:props.initialValue || '默认值'
};
// ES6 类中函数必须手动绑定
this.handleChange = this.handleChange.bind(this);
}
hide(){//因为是类,所以属性和方法之间不必添加都好
this.setState({
visible:false,
});
}
handleVisibleChange(visible){
this.setState({
visible
})
}
handleChange(event) {
this.setState({
text: event.target.value
});
}
render(){
const { dataurl } = this.props;
return (
<div>
Type something:
<input onChange={this.handleChange}
value={this.state.text} />
</div>
)
}
}
InputControlES6.propTypes = {
initialValue: React.PropTypes.string
};
InputControlES6.defaultProps = {
initialValue: ''
};
以上两者区别
A、React.createClass创建的组件,其每一个成员函数的this都有React自动绑定,任何时候使用,直接使用this.method即可,函数中的this会被正确配置。
React.Component
创建的组件,其成员函数不会自动绑定this,需要开发者手动绑定,否则this不能获取当前组件实例对象。
解决方案:this.handleClick = this.handleClick.bind(this); //构造函数中绑定
B、组件属性类型propTypes 及其默认props属性 defaultProps配置不同
React.createClass 在创建组件是,有关组件props 的属性类型及 组件默认的属性 会作为 组件实例的属性 来配置,其中defaultProps是使用 getDefaultProps 的方法是获取默认组件属性的
React.Component 在创建组件是配置这两个对应信息是,他们是作为组件类的属性,不是组件实例的属性,也就是所谓的类的静态属性来配置的。
C、React.createClass创建的组件,其状态state 是通过getInitialState 方法来配置组件相关的状态;React.Compnent 创建的组件,其状态state是在 constructor 中初始化组件属性一样的声明的
三、函数定义的无状态函数式组件
function HelloComponent(props){
return <div>Hello {props.name}</div>
}
ReactDOM.render(<HelloComponent name='component1' />,mountNode);
优点:1组件不会被实例化,整理渲染性能得到提升
2.组件不能访问到this
3.组件无生命周期
4.无状态组件智能访问输入的props
参考文档
https://www.cnblogs.com/wonyun/p/5930333.html