不論是React還是React-native,facebook官方都推薦使用ES6的語法,沒在項目中使用過的話,突然轉換過來會遇到一些問題,如果還沒有時間系統的學習下ES6那么注意一些常見的寫法暫時也就夠用的,這會給我們的開發帶來很大的便捷,你會體驗到ES6語法的無比簡潔。下面給大家介紹es6在react中的應用,具體內容如下所示:
import React,{Component} from 'react';class RepeatArrayextends Component{ constructor() { super(); } render(){ const names = ['Alice', 'Emily', 'Kate']; return ( <div> { names.map((name) =>{return <div>Hello, {name}!</div>;} ) } </div>);}}export default RepeatArray;二、ol與li的實現
import React,{Component} from 'react';class RepeatLiextends Component{ render(){ return ( <ol> { this.props.children.map((child)=>{return <li>{child}</li>}) } </ol>);}}class RepeatArray extends Component{constructor() {super();}render(){return (<div><RepeatLi><span>hello</span> <span>world</span></RepeatLi> </div>);}}export default RepeatArray;三、從服務端獲取數據
import React,{Component} from 'react';class UserGistextends Component{ constructor(){ super(); this.state={ username:'', lastGistUrl:'' } } componentWillMount(){ $.get(this.props.source, function(result){ var lastGist = result[0]; //if (this.isMounted()) { this.setState({ username: lastGist.owner.login, lastGistUrl: lastGist.html_url }); //} }.bind(this)); } render(){ return( <div> {this.state.username} .. <a href={this.state.lastGistUrl} >here</a></div> ); }}class RepeatArrayextends Component{ constructor() { super(); } render(){ return ( <div> <UserGist source="https://api.github.com/users/octocat/gists" /> </div>);}}export default RepeatArray;四、初始化STATE
class Videoextends React.Component{ constructor(props){ super(props); this.state = { loopsRemaining: this.props.maxLoops, }; }}五、解構與擴展操作符
在給子組件傳遞一批屬性更為方便了。下面的例子把 className 以外的所有屬性傳遞給 div 標簽
class AutoloadingPostsGridextends 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> ); }}使用 react 開發最常見的問題就是父組件要傳給子組件的屬性較多時比較麻煩
新聞熱點
疑難解答
圖片精選