新搭建的个人博客,本文地址:
在一开始的时候webpack配置中我们就加入了es2015的支持,就是下面的配置,但之前的学习笔记都使用的es5完成,所以专门作一篇笔记,记录使用es6完成CommentBoxquery: { presets: ['es2015','react']}
1、创建相关文件
touch src/commentEs6.js//修改webpack,增加该入口文件 entry:{ 'index':'./src/index.js', 'comment':'./src/comment.js', 'commentEs6':'./src/commentEs6.js', },//修改build/index.html,引入该文件
2、做个简单的测试,看下浏览器
//require全部用import来完成import React from 'react';import ReactDom from 'react-dom';//es6支持类,通过类继承完成组件的开发class CommentBox extends React.Component { render () { returnHello World}}//渲染ReactDom.render(,document.getElementById('content'))
3、直接贴出完整修改后的代码
import React from 'react';import ReactDom from 'react-dom';import marked from 'marked'import $ from 'jquery'class CommentBox extends React.Component { constructor(props){ super(props) //state 初始化直接在构造函数完成 this.state = {data:[]} } //函数的书写方式也发生了变化 loadCommentsFromServer(){ //还不太明白,总之this到了ajax中指向的对象就发生了变化 var url = this.props.url $.ajax({ url:url, dataType:"json", cache:false, //利用箭头函数传参,可以少去了bind this success:(data) => { this.setState({data: data}) }, error:(xhr,status,err) => { console.log(url,status,err.toString()) } }) } handleSubmitComment(data){ var url = this.props.url $.ajax({ url:url, type:"POST", data:data, dataType:"json", cache:false, success:(data) => { this.setState({data:this.state.data.concat(data)}); }, error:(xhr,status,err) => { console.log(this.props.url,status,err.toString()) } }) } componentDidMount(){ this.loadCommentsFromServer() //setTimeout(this.loadCommentsFromServer,2000) } render() { return () }}ReactDom.render() }}class CommentList extends React.Component{ constructor(props) { super(props) } render(){ var commentNodes = this.props.data.map(function(comment){ return (Comments
{comment.text} ) }); return ({commentNodes}) }}class Comment extends React.Component { constructor(props) { super(props) } rawMarkup(){ var rawMarkup = marked(this.props.children.toString(),{sanitize:true}) return {__html:rawMarkup} } render(){ return () }}class CommentForm extends React.Component{ constructor(props) { super(props) this.state = {author:"",text:""} } handleAuthorChange(event){ this.setState({author:event.target.value}) } handleTextChange(event){ this.setState({text:event.target.value}) } handleSubmit(event){ event.preventDefault(); var author = this.state.author.trim() var text = this.state.text.trim() if(!text||!author) { return; } this.props.onSubmitComment({author:author,text:text}); this.setState({author:"",text:""}) return false; } render(){ return ({this.props.author}