// The ES5 wayvarPhoto=React.createClass({handleDoubleTap:function(e){…},render:function(){…},});// The ES6+ wayclassPhotoextendsReact.Component{handleDoubleTap(e){…}render(){…}}
// The ES5 wayvarEmbedModal=React.createClass({componentWillMount:function(){…},});// The ES6+ wayclassEmbedModalextendsReact.Component{constructor(props){super(props);// Operations usually carried out in componentWillMount go here// 所有componentWillMount的操作都放在这里}}
// The ES5 wayvarVideo=React.createClass({getDefaultProps:function(){return{autoPlay:false,maxLoops:10,};},getInitialState:function(){return{loopsRemaining:this.props.maxLoops,};},propTypes:{autoPlay:React.PropTypes.bool.isRequired,maxLoops:React.PropTypes.number.isRequired,posterFrameSrc:React.PropTypes.string.isRequired,videoSrc:React.PropTypes.string.isRequired,},});// The ES6+ wayclassVideoextendsReact.Component{staticdefaultProps={autoPlay:false,maxLoops:10,}staticpropTypes={autoPlay:React.PropTypes.bool.isRequired,maxLoops:React.PropTypes.number.isRequired,posterFrameSrc:React.PropTypes.string.isRequired,videoSrc:React.PropTypes.string.isRequired,}state={loopsRemaining:this.props.maxLoops,}}
// Autobinding, brought to you by React.createClassvarPostInfo=React.createClass({handleOptionsButtonClick:function(e){// Here, 'this' refers to the component instance.this.setState({showOptionsModal:true});},});
// Manually bind, wherever you need toclassPostInfoextendsReact.Component{constructor(props){super(props);// Manually bind this method to the component instance...this.handleOptionsButtonClick=this.handleOptionsButtonClick.bind(this);}handleOptionsButtonClick(e){// ...to ensure that 'this' refers to the component instance here.this.setState({showOptionsModal:true});}}
The body of ES6 arrow functions share the same lexical this as the code that surrounds them, which gets us the desired result because of the way that ES7 property initializers are scoped. Peek under the hood to see why this works.
Often when composing components, we might want to pass down most of a parent component’s props to a child component, but not all of them. In combining ES6+ destructuring with JSX spread attributes, this becomes possible without ceremony:
常常当我们组合组件时,我们也许想要将父组件的大部分属性传递到子组件中,但是并不是全部。结合ES6+的destructuring和JSX spread attributes,这变成可能且不太复杂:
1234567891011121314
classAutoloadingPostsGridextendsReact.Component{render(){var{className,...others,// contains all properties of this.props except for className}=this.props;return(<divclassName={className}><PostsGrid{...others}/><buttononClick={this.handleLoadMoreClick}>Loadmore</button></div>);}}