移动端h5开发

React基础教程实例代码

2016-09-29  本文已影响328人  深海泰坦

一楼给敬佩的阮老师

React实例教程地址

引入原则:

<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/bable'>
  //**our codes goes here!
</script>

实际上线用babel进行转换

bable src --out-dir build

ReactDOM.render()

示例:

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

JSX语法

var names =['Alice','Emily','Kate'];

ReactDOM.render(
  <div>
  {
     names.map(function(name){
        return <div>Hello,{name}!</div>
    })
  }
  </div>,
  document.getElementById('example')
);

JSX允许在模板中直接插入JavaScript变量

var arr = [
   <h1>Hello world!</h1>,
   <h2>React is awesome</h2>
   ];
ReactDOM.render(
  <div>{arr}</div>,
  document.getElementById('example')
);

组件

React.createClass用于生成一个组件类

var HelloMessage = React.creatClass({
    render:function(){
    return <h1>Hello {this.props.name}</h1>;
    }
});

ReactDOM.render(
  <HelloMessage name='john' />,
  document.getElementById('example')
);

this.props.children

this.props.children 表示组件所有的子节点

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

ReactDOM.render(
  <NoteList>
    <span>hello</span>
    <span>World</span>
  </NoteList>,
  document.body
);

使用React.Children.map来遍历子节点,不用担心this.props.children的数据类型

PropTypes

验证实例的属性是否符合要求

var MyTitle = react.createClass({
   propTypes:{
     title:React.PropTypes.string.isRequired,
     },
   render:function(){
      return <h1>{this.props.title}</h1>
     }
});

var data = 123;

ReactDOM.render(
  <MyTitle title={data} />,
  document.body
 );
     

getDefaultProps可以用来设置组件属性的默认值

getDefaultProps:function(){
   return {
      title: 'Hello World'
      };
  }

获取真实的DOM节点

有时需要从组件中获取真实的DOM节点,需要用到ref属性。

var MyComponet = React.CreatClass({
   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>
      );
    }
});

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

指定click事件回调函数,确保DOM真实渲染后触发,除此还支持KeyDown等事件

this.state

组件视为状态机,用户互动,状态变化,重新渲染UI。

var LikeButton = React.CreatClass({
   getInitialState:function(){
        return {liked:false};
    },
   handleClick:function(event){
        this.setState({liked: !this.state.liked});
    },
   render:function(){
        var text = this.state.liked? 'like':'haven\'t liked';
        return(
           <p onClicked={this.handleClick}>
              You {text} this. Click to toggle.
           </p>
        );
    }
});

ReactDom.render(
   <LikeButton />,
   document.body
);

this.props表示一旦定义不再更改的属性,this.state表示随用户互动产生变化的特性。

表单

var Input = React.createClass({
    getInitialState:function(){
        return {value:'Hello!'};
    },
    handleChange:function(event){
        this.setState({value:event.target.value});
    },
    render:function(){
        var value = this.state.value;
        return (
           <div>
              <input type='text' value = {value}  
              onChange = {this.handleChange} />
              <p>{value}</p>
            </div>
        );
    }
});

ReactDOM.render(<Input />,document.body);

这里取得输入框的值没有使用this.props.value,选用了event.target.value。

组件的生命周期

var Hello = React.createClass({
    getInitialState:function()
        return {
           opacity:1.0
        }
    },
    
    compontentDidMount: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>
        );
    }
});

ReactDOM.render(
   <Hello name='world' />,
   document.body
);

bind(this)——原生JS写法。

Ajax

使用compontentDidMount方法设置Ajax请求

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 = 'http:xx.xxx.com' />,
    document.body
);
    

把其他途径获取的对象传入组件

ReactDOM.render(
    <RepoList promise = {$.getJSON('http://xx.xxx.com)} />,
    document.body
);

var RepoList = React.createClass({
    getInitialState: function(){
        return { loading:true, error : null , data : null}
    },
    
    componentDidMount(){
        this.props.promise.then(
            value => this.setState({loading:false,data:value}),
            error => this.setState({loading:false,error:error}));
    },
    
    render:function(){
        if(this.state.loading){
           return <span>Loading…</span>
        }
        else if(this.state.error !== null){
           return <span>Error: {this.state.error.message}</span>;
        }
        else{
           var repos = this.state.data.items;
           var reposList = repos.map(function(repo){
               return (
                  <li>
                     <a href={repo.html}>{repo.name}</a>
                  </li>
                );
            });
            return (
                <main>
                   <h1>Most Popular JavaScript Projects in Github</h1>
                   <ol>
                      {repoList}
                   </ol>
                </main>
            );
        }
    }
});
                    
上一篇下一篇

猜你喜欢

热点阅读