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的组件化思想,和组件的生命周期。

相关文章

react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接...
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc ...