不论是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> ); } }
内容版权声明:除非注明,否则皆为本站原创文章。