参考:http://www.mrfront.com/2017/01/11/react-writing-compare/
1. 由React.createClass变为React.Component
var SwitchButton = React.createClass({})
class SwitchButton extends React.Component {}
2.状态写法
getInitialState: function() { return { open: this.props.open };}
更改为:
constructor(props) {
super(props)
this.state = {open: this.props.open}
}
getDefaultProp:function() { return { open: false }}
更改为:
SwitchButton.defaultProps = { open: false}
3.导入模块部分
var React = require('react');
var ReactDOM = require('react-dom');
更改为:
import React from 'react'
import { render } from 'react-dom'
4.事件函数绑定
React.Component创建组件时,事件函数并不会自动绑定this,需要我们手动绑定,不然this将不会指向当前组件的实例对象。以下有三种绑定this的方法:
(1)在constructor中使用bind()进行绑定:
constructor() {this.handleClick = this.handleClick.bind(this);}
(2)直接元素上绑定:<label className={className} onClick={this.handleClick.bind(this)}>
(3)箭头符号:<label className={className} onClick={()=>this.handleClick()}>
5.无状态组件(Stateless Component)–SFC
它的出现 是因为随着应用复杂度不断提升和组件本数量的增加,组件按各自职责被分成不同的类型,于是有一种只负责展示的纯组件出现了,它的特点是不需要管理状态state,数据直接通过props传入,这也符合 React 单向数据流的思想。
const Todo = ({ onClick, complete, text, ...props }) => (
<li
onClick={onClick}
style={{textDecoration: complete ? "line-through" : "none"}}
{...props}>
{props.text}
</li>
)
当然,无状态组件也不是万金油,比如它不支持”ref“,原因很简单,因为 React 调用它之前,组件不会被实例化,自然也就没有”ref”,(ref和findDOMNode实际上打破了父子组件之间仅通过 props 来传递状态的约定,违背了 React 的原则,需要避免)。
React.createClass亲生的 mixin,React.Component不再支持,事实上 mixin 不够优雅直观,替代方案是使用更流行的高阶组件-HOC,如果你的项目还离不开 也可以使用 react-mixin