React 序曲和一个Note App

-- React prologue and Build a note app #post title

tutorial video

  1. Download code: https://github.com/buckyroberts/React-Boilerplate, My editon with notes: https://github.com/xy7313/React-Boilerplate. Final note app click here, code here

  2. Include JSX

//after download, also can ref online file,
<script src="../../js/react.min.js"></script>
<script src="../../js/react-dom.min.js"></script>
<script src="../../js/browser.min.js"></script>

The last line transpile jsx file to plain js file so that browser can understand jsx. There are also some online tools can do the same work for developer.

  • an example:
     <!DOCTYPE html>
     <html>
    
       <head>
         <script data-require="react@*" data-semver="15.5.0" src="https://cdnjs.cloudflare.com/ajax/libs/react/15.5.0/react.min.js"></script>
         <script data-require="react@*" data-semver="15.5.0" src="https://cdnjs.cloudflare.com/ajax/libs/react/15.5.0/react-dom.min.js"></script>
         <script data-require="react@*" data-semver="15.5.0" src="    https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js"></script>
         <link rel="stylesheet" href="style.css" />
       </head>
    
       <body>
    
         <div id="container"></div>
    
         <script type="text/babel">
             ReactDOM.render(
                 <h2>Welcome to React!</h2>,
                 document.getElementById('container')
             );
         </script>
    
       <script src="script.js"></script>
       </body>
    
     </html>
    
  1. Include bable: we add a h2 tag into the html element whoes id is 'container'
 <script type="text/babel">
        ReactDOM.render(
            <h2>Welcome to React!</h2>,
            document.getElementById('container')
        );
</script>
  1. Components parts of your website, entire application is made up of components.

  2. Super component:

<script type="text/babel">
    var BuckysComponent = React.createClass({
        //object
        //return html
        render: function() {
            return (<h2>This is a simple component</h2>);
        }
    });
    ReactDOM.render(<BuckysComponent />, document.getElementById('container'));
</script>
  1. Mutiple components
  • One component can only return one parent element(div). The render ReactDOM.render(..,..)can only render only one one parent tag
  • when we want to return more than one html tags.
<script type="text/babel">
   var BuckysComponent = React.createClass({
       //object
       //return html
       render: function() {
           return (
              <div>
                  <h2>This is a simple component</h2>
                  <p>para</p>
              </div>
          );   
       }
   });
   ReactDOM.render(<div>
                    <BuckysComponent />
                    <BuckysComponent />
                </div>, document.getElementById('container'));
</script>
  1. Properties:
  • make template for one component and customize in different ways. Using curly brace{}

  • Property is essentially an HTML attribute that we can pass in to customize our components in different kinds of ways.

    <body>
    
       <div id="container"></div>
    
       <script type="text/babel">
         var Movie = React.createClass({ 
           render:function(){
             return(
                     <div>
                       <h1>{this.props.title}</h1>
                       <h2>{this.props.genre}</h2>
                     </div>
               );
           }
         });
           ReactDOM.render(
             <div>
               <Movie title="Avatar" genre="action"/>
               <Movie title="The NoteBook" genre="romance"/>
               <Movie title="Cube" genre="thriller"/>
             </div>,document.getElementById('container')
           );
       </script>
    
     </body>
    //output: Avatar, action, The NoteBook, romance, Cube, thriller
    
  1. Event handling
  • Example: Built a sticky note app, where users can add new notes, delete or edit notes and write any notes.

  • can not use class as prop's name, because class is one of the reserve words in js

  • children property(built-in prop), between the opening tag and closing tag, like: <Comment>hey-sample txt</Comment>

    <!DOCTYPE html>
    <html>
    
     <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>React-stickyNote</title>
        <script src="../../js/react.min.js"></script>
        <script src="../../js/react-dom.min.js"></script>
        <script src="../../js/browser.min.js"></script>
        <link rel = "stylesheet" type="text/css" href = "../../css/main.css">
      </head>
    
      <body>
    
        <div id="container"></div>
    
        <script type="text/babel">
          var Comment = React.createClass({ 
            edit: function(){
              alert("edit");
            },
            remove: function(){
              alert("remove");
            },
            render: function(){
              return(
                //can not use class, because class is reserve word in js
                 //children property, between the opening tag and closing tag
                      <div className = "commentContainer">
                        <div className = "commentText"> {this.props.children} </div>
                        <button  onClick={this.edit} className = "button-primary">Edit</button>
                        <button onClick={this.remove} className = "button-danger" >Remove</button>
                      </div>
                );
            }
          });
            ReactDOM.render(
              <div className = "board">
                <Comment>hey-sample txt</Comment>
                <Comment>beans</Comment>
                <Comment>TUNA txt</Comment>
              </div>,document.getElementById('container')
            );
        </script>
    
      </body>
    
    </html>
    
  1. State
  • Customize the components using properties and states. Whenever something is gonna stay the same uses properties, whenever changes uses states.

  • You don't need to explicitly say whenever your state changes to redraw a certain part of your webpage, it automatically watches for your states. Whenever their state changes, the part of web page gets redrawn automatically to fit that.

    <body>
    
       <div id="container"></div>
    
       <script type="text/babel">
    
         var CheckBox = React.createClass({ 
    
           getInitialState: function(){
               return {checked:true}
           },
           handleChecked: function(){
               this.setState({checked:!this.state.checked})
           },
           render: function(){
               var msg;
               if(this.state.checked){
                   msg='checked'
               }else{
                   msg='unchecked'
               }
    
              return(
                      <div className = "commentContainer">
                        <input type = "checkbox" defaultChecked={this.state.checked} onChange = {this.handleChecked}/>
                        <h3>checkBox is {msg}</h3> 
                      </div>
                );
           }
         });
           ReactDOM.render(
             <CheckBox />,document.getElementById('container')
           );
       </script>
    
     </body>
    
  1. Add state to component(contd on the sticky note app)
  • Requirements: This note switches bewteen two modes/states: editing, normal. That is, whenever we click edit, the text area can be changed to a form for editing. After complish editing, the form turns to text area.

     <body>
    
       <div id="container"></div>
    
       <script type="text/babel">
         var Comment = React.createClass({ 
           getInitialState: function(){
             return {editing: false}
           },
           edit: function(){
             this.setState({editing:true});
           },
           save: function(){
             this.setState({editing:false});
           },
           remove: function(){
             alert("remove");
           },
    
           renderForm: function(){
             return(
                     <div className = "commentContainer">
                      <textarea defaultValue = {this.props.children}></textarea>
                       <button onClick={this.save} className = "button-success" >Save</button>
                     </div>
               );
           },
           renderNormal: function(){
             return(
                     <div className = "commentContainer">
                       <div className = "commentText"> {this.props.children} </div>
                       <button  onClick={this.edit} className = "button-primary">Edit</button>
                       <button onClick={this.remove} className = "button-danger" >Remove</button>
                     </div>
               );
           },
           render: function(){
             if(this.state.editing){
               return this.renderForm();
             }else{
               return this.renderNormal();
             }
           }
         });
           ReactDOM.render(
             <div className = "board">
               <Comment>hey-sample txt</Comment>
               <Comment>beans</Comment>
               <Comment>TUNA txt</Comment>
             </div>,document.getElementById('container')
           );
       </script>
    
     </body>
    
  1. refs (contd on the sticky note app)
  • Requirements: Save whatever the textarer looks like now.
  • First, get the text just typed
  • Second, show it
  • eg: var val = this.refs.newText.value; + <textarea ref = "newText" defaultValue = {this.props.children}></textarea>
  1. rearrange multiple independent components -- set up a 'parent' container (contd on the sticky note app)
  • In the note example, we define a borad, which is like a magener of all note components
  • unique identifier, key is the way to uniquely identify each child by giving an ID
//add Board in script babel, change ReactDom.render
var Board = React.createClass({
       getInitialState: function(){
         return {
           comments:[
                   'I like bacon',
                   'want some ice cream',
                   'done here'

           ]
         };
       },
       render: function(){
         return (
            <div className = "board">
             {
             //anonymous  function, a.k.a a function with no name, key-unique identifier
               this.state.comments.map(function(text,i){
                 return (<Comment key = {i}>{text}</Comment>);
               })
             }
           </div>
         );
       }
     });

       ReactDOM.render(<Board/> ,document.getElementById('container')
       );
  1. Updating state and remove notes(contd on the sticky note app)
  • clean up the render function
  • array.splice(index,num); remove num elements from index of array
//all in var Board
removeComment: function(i){
    console.log("remove:"+i);
    var arr = this.state.comments;
    arr.splice(i,1);
    this.setState({comments:arr});
  },
  updateComment: function(newText,i){
    console.log("new text:"+newText);
    var arr = this.state.comments;
    arr[i] = newText;
    this.setState({comments:arr});
  },
  eachComment: function(text,i){
    // unique identifier, i: increment for the array
    return (<Comment key = {i} index = {i}>
              {text}
            </Comment>);
  },
  render: function(){
    return (
       <div className = "board">
        {this.state.comments.map(this.eachComment)}
      </div>
    );
  }
  1. Passing functions as props (contd on the sticky note app)
  • how to call functions from entirely different components? using props
  1. Add new component (contd on the sticky note app)
  1. Js can not figure out the scope, so we need to call band : <button className = "button-info create" onClick = {this.addComment.bind(null,'Type here')}>New A Comment</button>.
    Notice that: Don't .bind in the render() function - that creates a new function every time render is called (which will be often.) .bind in the component constructor. We will create too many comment components and get an error.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,921评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,635评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,393评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,836评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,833评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,685评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,043评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,694评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,671评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,670评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,779评论 1 332
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,424评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,027评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,984评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,214评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,108评论 2 351
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,517评论 2 343

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,372评论 0 23
  • 一个能够放下自尊去做事情的人,看的是目标结果;然而过分强调自尊的人,在做事情的时候,总是希望有人陪自己做同样的工作...
    peter_621f阅读 193评论 0 1
  • 白风盯着纸张上的苍蝇,过了多久了?十五秒还是二十秒?自己似乎对时间的从来都没有概念,总觉得时间的“嘀嗒”像是在嘲笑...
    一浮生阅读 204评论 0 0
  • 前几天和一个朋友聊天,我突然意识到,之前我对待好多事情的方法可能是错的。朋友说,“妈妈说,要学会克制,把事情写在纸...
    _浅墨_阅读 826评论 0 0
  • 有些问题不回答就是不想说 刻意重复提问显得具有攻击性 两人之间的舒适感本身很难建立 更别说维持
    sam_阅读 153评论 0 0