React.js中常用的ES6寫法總結(jié)(推薦)
一 模塊
1 引入模塊以便使用
用import實現(xiàn):
import '模塊文件地址' import 組件 from '模塊文件地址'
2 導(dǎo)出模塊
用export default實現(xiàn):
export default class MyComponent extends Component{
...
}
引用:
import MyComponent from './MyComponent';
二 組件
1 定義組件
通過定義一個繼承自React.Component的class來定義一個組件類:
class Photo extends React.Component {
render() {
...
}
}
2 定義組件方法
直接用名字(){},很像Java定義類方法的寫法:
class Photo extends React.Component {
componentWillMount() {
}
render() {
return (
<Image source={this.props.source} />
);
}
}
3 定義組件的屬性類型和默認屬性
統(tǒng)一使用static成員來實現(xiàn):
class Video extends React.Component {
static defaultProps = {
autoPlay: false,
maxLoops: 10,
}; // 注意這里有分號
static propTypes = {
autoPlay: React.PropTypes.bool.isRequired,
maxLoops: React.PropTypes.number.isRequired,
posterFrameSrc: React.PropTypes.string.isRequired,
videoSrc: React.PropTypes.string.isRequired,
}; // 注意這里有分號
render() {
return (
<View />
);
} // 注意這里既沒有分號也沒有逗號
}
注意: 對React而言,static成員在IE10及之前版本不能被繼承,而在IE11和其它瀏覽器上可以,有時會帶來一些問題。React Native則不用擔(dān)心這個問題。
4 初始化STATE
在構(gòu)造函數(shù)中初始化(這樣可以根據(jù)需要做一些計算):
class Video extends React.Component {
constructor(props){
super(props);
this.state = {
loopsRemaining: this.props.maxLoops,
};
}
}
5 把方法作為回調(diào)提供并使用
ES5下可以這么做:
//ES5
var PostInfo = React.createClass({
handleOptionsButtonClick: function(e) {
// Here, 'this' refers to the component instance.
this.setState({showOptionsModal: true});
},
render: function(){
return (
<TouchableHighlight onPress={this.handleOptionsButtonClick}>
<Text>{this.props.label}</Text>
</TouchableHighlight>
)
},
});
在ES5下,React.createClass會把所有的方法都bind一遍,這樣可以提交到任意的地方作為回調(diào)函數(shù),而this不會變化。但官方現(xiàn)在認為這是不標(biāo)準(zhǔn)、不易理解的。
ES6下,需要通過bind來綁定this引用,或者使用箭頭函數(shù)(它會綁定當(dāng)前scope的this引用)來調(diào)用:
//ES6
class PostInfo extends React.Component
{
handleOptionsButtonClick(e){
this.setState({showOptionsModal: true});
}
render(){
return (
<TouchableHighlight
onPress={this.handleOptionsButtonClick.bind(this)}
onPress={e=>this.handleOptionsButtonClick(e)}
>
<Text>{this.props.label}</Text>
</TouchableHighlight>
)
},
}
箭頭函數(shù)是在這里定義了一個臨時的函數(shù),箭頭函數(shù)的箭頭=>之前是一個空括號、單個的參數(shù)名、或用括號括起的多個參數(shù)名,而箭頭之后可以是一個表達式(作為函數(shù)的返回值),或者是用花括號括起的函數(shù)體(需要自行通過return來返回值,否則返回的是undefined)。
即:箭頭函數(shù)箭頭前是參數(shù),箭頭后是函數(shù)體或返回值。
注意:
不論是bind還是箭頭函數(shù),每次被執(zhí)行都返回的是一個新的函數(shù)引用,因此如果你還需要函數(shù)的引用去做一些別的事情(譬如卸載監(jiān)聽器),那么必須自己保存這個引用:
// 錯誤的做法
class PauseMenu extends React.Component{
componentWillMount(){
AppStateIOS.addEventListener('change', this.onAppPaused.bind(this));
}
componentDidUnmount(){
AppStateIOS.removeEventListener('change', this.onAppPaused.bind(this));
}
onAppPaused(event){
}
}
// 正確的做法
class PauseMenu extends React.Component{
constructor(props){
super(props);
this._onAppPaused = this.onAppPaused.bind(this);//注意這里
}
componentWillMount(){
AppStateIOS.addEventListener('change', this._onAppPaused); //還有這里
}
componentDidUnmount(){
AppStateIOS.removeEventListener('change', this._onAppPaused);
}
onAppPaused(event){
}
}
三 Mixins
ES5下,經(jīng)常使用mixin來為類添加一些新的方法,如PureRenderMixin:
var PureRenderMixin = require('react-addons-pure-render-mixin');
React.createClass({
mixins: [PureRenderMixin],
render: function() {
return <div className={this.props.className}>foo</div>;
}
});
但React官方已經(jīng)不再打算在ES6里繼續(xù)推行Mixin,官方推薦,對于庫編寫者而言,應(yīng)盡快放棄Mixin的編寫方式,推薦一種新的編碼方式:
//Enhance.js
import { Component } from "React";
export var Enhance = ComposedComponent => class extends Component {
constructor() {
this.state = { data: null };
}
componentDidMount() {
this.setState({ data: 'Hello' });
}
render() {
return <ComposedComponent {...this.props} data={this.state.data} />;
}
};
//HigherOrderComponent.js
import { Enhance } from "./Enhance";
class MyComponent {
render() {
if (!this.data) return <div>Waiting...</div>;
return <div>{this.data}</div>;
}
}
export default Enhance(MyComponent); // Enhanced component
用一個“增強函數(shù)”,來為某個類增加一些方法,并且返回一個新類,這無疑能實現(xiàn)mixin所實現(xiàn)的大部分需求。
四 解構(gòu)與屬性延展
結(jié)合使用ES6+的解構(gòu)和屬性延展,在給子組件傳遞一批屬性更為方便了。下面的例子把className以外的所有屬性傳遞給div標(biāo)簽:
class AutoloadingPostsGrid extends React.Component {
render() {
var {
className,
...others, // contains all properties of this.props except for className
} = this.props;
return (
<div className={className}>
<PostsGrid {...others} />
<button onClick={this.handleLoadMoreClick}>Load more</button>
</div>
);
}
}
下面這種寫法,則是傳遞所有屬性的同時,用新的className值進行覆蓋({…this.props}寫在前邊):
<div {...this.props} className="override">
…
</div>
這個例子則相反,如果屬性中沒有包含className,則提供默認的值,而如果屬性中已經(jīng)包含了,則使用屬性中的值({…this.props}寫在后邊)
<div className="base" {...this.props}>
…
</div>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
React styled-components設(shè)置組件屬性的方法
這篇文章主要介紹了styled-components設(shè)置組件屬性的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-08-08
React?TypeScript?應(yīng)用中便捷使用Redux?Toolkit方法詳解
這篇文章主要為大家介紹了React?TypeScript?應(yīng)用中便捷使用Redux?Toolkit方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-11-11
React Native 集成jpush-react-native的示例代碼
這篇文章主要介紹了React Native 集成jpush-react-native的示例代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-08-08
webpack構(gòu)建react多頁面應(yīng)用詳解
這篇文章主要介紹了webpack構(gòu)建react多頁面應(yīng)用詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09
react-router JS 控制路由跳轉(zhuǎn)實例
這篇文章主要介紹了react-router JS 控制路由跳轉(zhuǎn)實例,react實現(xiàn)路由可以直接使用react-router。有興趣的可以了解一下2017-06-06
TypeScript在React項目中的使用實踐總結(jié)
這篇文章主要介紹了TypeScript在React項目中的使用總結(jié),本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-04-04

