ReactJS入门ES6写法

7 篇文章 0 订阅
6 篇文章 0 订阅

参考:
React 官方网站
ECMAScript 6 入门
React 入门实例教程

HTML 模板
使用 React 的网页源码,结构大致如下。

<!DOCTYPE html>
<html>
  <head>
    <script src="../build/react.js"></script>
    <script src="../build/react-dom.js"></script>
    <script src="../build/browser.min.js"></script>
  </head>
  <body>
    <div id="example"></div>
    <script type="text/babel">
      // ** Our code goes here! **
    </script>
  </body>
</html>

1.输出”Hello“

//ES5
 ReactDOM.render(
   <h1>Hello, world!</h1>,
   document.getElementById('example')
 );

//ES6
 class HelloMessage extends React.Component{
   render(){
     return <h1>Hello {this.props.name}</h1>;
   }
 }
 class Output extends React.Component{
   render(){       
     return (
       <div>
           <HelloMessage name="John" />
       </div>
     );
   }
 }
 ReactDOM.render(<Output />,document.getElementById('example'));

2.数组遍历

 //ES5
 var names = ['Alice', 'Emily', 'Kate'];
 ReactDOM.render(
    <div>
    {
      names.map(function (name) {
        return <div>Hello, {name}!</div>
      })
    }
    </div>,
    document.getElementById('example')
  );

//ES6
class Greeting extends React.Component {      
   render() {
     const names = ['Alice', 'Emily', 'Kate'];
     return (
       <div>
       {
         names.map((name,index) => <div key = {index}>Hello, {name}!</div>)
       }
       </div>
     );
   }
 }
 ReactDOM.render(<Greeting />,document.getElementById('example'));

3.this.props.children
组件类的 this.props属性,可以在组建对象上获取,
this.props 对象的属性与组件的属性一一对应,但是有一个例外,就是 this.props.children 属性。它表示组件的所有子节点

//ES5
var NotesList = React.createClass({
  render: function() {
    return (
      <ol>
      {
        React.Children.map(this.props.children, function (child) {
          return <li>{child}</li>;
        })
      }
      </ol>
    );
  }
});

//ES6
class NotesList extends React.Component {      
  render() {
    return (
      <ol>
        {
          React.Children.map(this.props.children, (child) => {return <li>{child}</li>})
        }
      </ol>
    )
  }
}

ReactDOM.render(
  <NotesList>
    <span>hello</span>
    <span>world</span>
  </NotesList>,
  document.body
);

4.PropTypes和defaultProps
定义组件的属性类型和默认属性,统一使用static成员来实现

//ES5
var Video = React.createClass({
    getDefaultProps: function() {
        return {
            autoPlay: false,
            maxLoops: 10,
        };
    },
    propTypes: {
        autoPlay: React.PropTypes.bool.isRequired,
        maxLoops: React.PropTypes.number.isRequired,
        posterFrameSrc: React.PropTypes.string.isRequired,
        videoSrc: React.PropTypes.string.isRequired,
    },
    render: function() {
        return (
            <View />
        );
    },
});
//ES6
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 />
        );
    } // 注意这里既没有分号也没有逗号
}

5.ref属性
从组件获取真实 DOM节点

//ES5
var MyComponent = React.createClass({
  handleClick: function() {
    this.refs.myTextInput.focus();
  },
  render: function() {
    return (
      <div>
        <input type="text" ref="myTextInput" />
        <input type="button" value="Focus the text input" onClick={this.handleClick} />
      </div>
    );
  }
});

//ES6
class MyComponent extends React.Component {
  constructor(props){
    super(props);
    this.handleClick = this.handleClick.bind(this)
  }
  handleClick(){
    this.refs.myTextInput.focus()
  }
  render(){
    return(
      <div>
        <input type="text" ref="myTextInput" />
        <input type="button" value="Focus the text input" onClick={this.handleClick} />
      </div>
    )
  }
}

ReactDOM.render(
  <MyComponent />,
  document.getElementById('example')
);

6.组件状态机 this.state
将组件看成是一个状态机,一开始有一个初始状态,然后用户互动,导致状态变化,从而触发重新渲染 UI

//ES5
var LikeButton = React.createClass({
  getInitialState: function() {
    return {
      liked: false,
      value: 'crlin'
    };
  },
  handleClick: function(event) {
    this.setState({liked: !this.state.liked});
  },
  handleChange: function(event) {
    this.setState({value: event.target.value});
  },
  render: function() {
    var text = this.state.liked ? 'like' : 'haven\'t liked',
        value = this.state.value;
    return (
      <div> 
        <p onClick={this.handleClick}>You {text} this. Click to toggle.</p>
        <input type="text" value={value} onChange={this.handleChange} />
        <p>{value}</p>
      </div>
    );
  }
});

//ES6
class LikeButton extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      liked: false,
      value: "crlin"
    }
  }
  handleClick(){
    this.setState({
      liked: !this.state.liked
    })
  }
  handleChange(event){
    this.setState({
      value: event.target.value
    })
  }
  render(){
    let text = this.state.liked ? 'like' : 'haven\'t liked',
        value = this.state.value;
    return (   
      <div> 
        <p onClick={this.handleClick.bind(this)}>You {text} this. Click to toggle.</p>
        <input type="text" value={value} onChange={this.handleChange.bind(this)} />
        <p>{value}</p>
      </div>
    );
  }
}
ReactDOM.render(
  <LikeButton />,
  document.getElementById('example')
);

7.Component Lifecycle(生命周期)
React Component Lifecycle(生命周期)

//ES5
var Hello = React.createClass({
  getInitialState: function () {
    return {
      opacity: 1.0
    };
  },

  componentDidMount: function () {
    this.timer = setInterval(function () {
      var opacity = this.state.opacity;
      opacity -= .05;
      if (opacity < 0.1) {
        opacity = 1.0;
      }
      this.setState({
        opacity: opacity
      });
    }.bind(this), 100);
  },

  render: function () {
    return (
      <div style={{opacity: this.state.opacity}}>
        Hello {this.props.name}
      </div>
    );
  }
});

//ES6
class Hello extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      opacity: 1.0
    }
  }

  componentDidMount() {
    let timer = setInterval( () => {
      let opacity = this.state.opacity;
      opacity -= .05;
      if (opacity < 0.1) {
        opacity = 1.0;
      }
      this.setState({
        opacity: opacity
      });
    }, 100);
  }

  render() {
    return (
      <div style={{opacity: this.state.opacity}}>
        Hello {this.props.name}
      </div>
    );
  }
};
ReactDOM.render(
  <Hello name="world"/>,
  document.getElementById('example')
);

8.ajax请求

可以使用 componentDidMount 方法设置 Ajax 请求,等到请求成功,再用 this.setState 方法重新渲染 UI

//ES5
var UserGist = React.createClass({
  getInitialState: function() {
    return {
      username: '',
      lastGistUrl: ''
    };
  },

  componentDidMount: function() {
    $.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: function() {
    return (
      <div>
        {this.state.username}'s last gist is
        <a href={this.state.lastGistUrl}>here</a>.
      </div>
    );
  }
});

ReactDOM.render(
  <UserGist source="https://api.github.com/users/octocat/gists" />,
  document.body
);

//ES6
class UserGist extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      username:'',
      lastGistUrl:''
    }
  }
  componentDidMount(){
    $.get(this.props.source, (result) => {
      let lastGist = result[0];    
        this.setState({
          username: lastGist.owner.login,
          lastGistUrl: lastGist.html_url
        });
    });
  }
  render(){
    return(
      <div>
        {this.state.username} ..
        <a href={this.state.lastGistUrl} >here</a>
      </div>
    );
  }
}
class RepeatArray extends React.Component{
  constructor(props) {
    super(props);
  }
  render(){
    return (
      <div>
      <UserGist source="https://api.github.com/users/octocat/gists" />
      </div>
    );
  }
}
ReactDOM.render(
  <RepeatArray/>,
  document.getElementById('example')
);
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值