React 入门笔记1

前端之家收集整理的这篇文章主要介绍了React 入门笔记1前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

下面的代码是取自阮一峰老师http://www.jb51.cc/article/p-rkowmlmt-bnx.html,稍加调试修改,记录在此。

1、打开浏览器 查看console终端的输出

<!DOCTYPE html>
<html>
  <head>
    <script src="../build/react.js"></script>
    <script src="../build/react-dom.js"></script>
    <script src="../build/browser.min.js"></script>
    <script src="../build/jquery.min.js"></script>
  </head>
  <body>
    <div id="example"></div>
    <script type="text/babel">
var UserGist = React.createClass({
  getInitialState: function() {
      console.log('here we are in getInitialState');
    return {
      username: '',lastGistUrl: ''
    };
  },componentDidMount: function() {  
      console.log('here we are in componentDidMount');

    $.get(this.props.source,function(result) {
      console.log('here we are in get');
      var lastGist = result[0];
      if (this.isMounted()) {
      console.log('yes,isMounted!');
        this.setState({
          username: lastGist.owner.login,lastGistUrl: lastGist.html_url
        });
        //一旦修改了state,马上就调用了render
        //所以下面这一行是在调用render之后才执行的
        console.log('after setState');

      }
    }.bind(this));
  },render: function() {
      console.log('here we are in render');

    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.getElementById('example')
);
    </script>
  </body>
</html>


2、同上

<!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">
var MyComponent = React.createClass({
  handleClick: function(e) {
    this.refs.myTextInput.focus();
  },getInitialState: function() {
    return {value: 'Hello!'};
  },update:function(e){
  this.setState({value:e.target.value});
  },render: function() {
    console.log("rendering!");
    return (
      <div>
        <input type="text" ref="myTextInput" onChange={this.update} />
        <input type="button" value="Focus the text input" onClick={this.handleClick} />
        <p>{this.state.value}</p>
      </div>
    );
  }
});

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


3、注意React的组件化思想,和组件的生命周期。

原文链接:https://www.f2er.com/react/306227.html

猜你在找的React相关文章