无状态函数式(stateless)
写法一
const Hello = (props) => (Hello {props.title} {props.name})
写法二
function HelloComponent(props, /* context */) { return (Hello {props.name})}ReactDOM.render(, mountNode)
ES5 React.createClass
var CommentBox = React.createClass({ getInitialState: function() { return {data: []}; }, componentDidMount: function() { }, render: function() { return (); }});
ES6 React.component
import React, {Component} from 'react'export class App extends Component { constructor(props) { super(props); } render() { return (//TODO); }}
注意:
React.component 创建的组件,其成员函数不会自动绑定 this
class Contacts extends Component { constructor(props) { super(props); } handleClick() { console.log(this); // null } render() { return ( ); }
其绑定 this 通常有3种方法
constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); //构造函数中绑定} //使用bind来绑定this.handleClick()}>//使用arrow function来绑定,自动捕捉其所在上下文或者在声明时使用箭头函数handleIncrement = counter => { const counters = [...this.state.counters]; const index = counters.indexOf(counter); counters[index] = {...counter}; counters[index].value++; this.setState({counters});};
1、只要有可能,尽量使用无状态组件创建形式。否则(如需要state、生命周期方法等),使用`React.Component`这种es6形式创建组件
2. 使用原生事件绑定,在组件销毁时需要手动移除监听