eact 创建组件的三种方式:
1, 函数式无状态组件
2,es5 方式 React.createClass 组件
3,es6 方式 extends React.Component
三种创建方式的异同
1, 函数式无状态组件
(1) 语法
- function myComponent(props) {
- return
- <div>Hello {props.name}</div>
- }
(2) 特点
● 它是为了创建纯展示组件, 这种组件只负责根据传入的 props 来展示, 不涉及到 state 状态的操作.
● 组件不能访问 this 对象
● 不能访问生命周期方法
(3) 建议
如果可能, 尽量使用无状态组件
2,es5 方式 React.createClass 组件
(1) 语法
- var myCreate = React.createClass({
- defaultProps: {
- //code
- },
- getInitialState: function() {
- return {
- //code
- };
- },
- render: function() {
- return (
- <div>
- //code
- </div>
- );
- }
- });// 欢迎加入全栈开发交流群一起学习交流: 864305860
(2) 特点
这种方式比较陈旧, 慢慢会被淘汰.
3,es6 方式 extends React.Component
(1) 语法
- class InputControlES6 extends React.Component {
- constructor(props) {
- super(props);
- this.state = {
- state_exam: 'hello'
- };
- // ES6 类中函数必须手动绑定
- this.handleChange = this.handleChange.bind(this);
- }
- handleChange() {
- this.setState({
- state_exam: 'hello world'
- });
- }
- render() {
- return (
- <div>
- //code
- </div>
- );
- }
- };// 欢迎加入全栈开发交流群一起学习交流: 864305860
(2) 特点
● 成员函数不会自动绑定 this, 需要开发者手动绑定, 否则 this 不能获取当前组件实例对象.
● 状态 state 是在 constructor 中像初始化.
● props 属性类型和组件默认属性作为组件类的属性, 不是组件实例的属性, 所以使用类的静态属性配置.
获取源码
来源: http://www.qdfuns.com/article/51117/1ca4b39d065fa14b07256709c42a1e8d.html