@gongzhen
2016-07-22T03:14:46.000000Z
字数 2048
阅读 6827
react
//es5var MyComponent = React.createClass({render: function() {return (<div></>);}});module.exports = MyComponent;//es6class MyComponent extends React.Component {render() {return (<div></>);}}export MyComponent Apply;
es6中没有getInitialState方法,设置state用constructor
//es5getInitialState: function() {return {speakersKey: 'shanghai'};},//es6constructor(props) {super(props);this.state = {speakersKey: 'shanghai'};}
//es5getInitialState: function() {return {speakersKey: 'shanghai'};},onTabItemSelectedChanged: function(item, index) {this.setState({speakersKey: item.key});},//以逗号结尾render: function() {return (<div></>);}//es6constructor(props) {super(props);this.state = {busy: false};}render() {return (<div></>);}//结尾没有逗号onClickForumItem(forum, index, forums, event) {forum.selected = !(forum.selected);event.currentTarget.className = forum.selected ? 'selected' : '';}
es6绑定事件时需要显示调用bind()方法设置组件上下文,es5不需要
//es5<div onClick={this.onItemClick}></div>//es6<div onClick={this.onItemClick.bind(this)}></div>
React里的事件参数传递和传统的JS参数有些不一样,需要通过bind方法来绑定参数,第一个参数指向this,第二个参数开始才是事件函数接收到的参数:
<button onClick={this.handleClick.bind(this, props0, props1, ...}></button>handleClick(porps0, props1, ..., event) {// your code here}
我们使用bind(this)显式的绑定了事件处理函数的运行上下文,当使用ES6 Class语法定义组件时,必须使用bind(this)显式的绑定事件处理函数的运行上下文
//es5require('./MyComponent.styl');var React = require('react');var MyComponent = React.createClass({getInitialState: function() {return {title: 'hi'};},onClickTitle: function() {this.setState({title: 'Hello'});},render: function() {return (<div className="my-component"><h1 onclick={this.onClickTitle}> {this.state.title} </h1></div>);}});module.exports = MyComponent;//es6import './MyComponent.styl';import React from 'react';class MyComponent extends React.Component {constructor(props) {super(props);this.state = {title: 'hi'};}onClickTitle() {this.setState({title: 'Hello'});}render() {return (<div className="my-component"><h1 onclick={this.onClickTitle.bind(this)}> {this.state.title} </h1></div>);}}export default MyComponent;