React.js基础知识

一、 react.js的基本使用方法

1)快速使用,hello world

<div id="app"></div>

<script src="bower_components/react/react.js"></script>

<script src="bower_components/react/JSXTransformer.js"></script>

<script type="text/jsx">

    var Message = React.createClass({          //创建组件,首字母必须大写

        clickMe: function () {               //此处方法可以在组件中直接使用

            alert('click again');

        },

        render: function () {

            return (<h1 onClick={this.clickMe} class="addd">hello world!</h1>)

        }});

//加载组件

React.render(

<Message/>,

document.getElementById('app'),

function () {

                  alert('success')

    })

</script>

2)组件的嵌套

//需要注意的是,当嵌套组件时,整个当前组件内容需要用标签包裹起来

    var Message1 = React.createClass({

        render: function () {

            var arr = [];

            for (var i = 0; i < 10; i++) {  //循环生成组件数组

                arr.push<Message2 key={'Meg'+i}/>);      //可以添加key进行区分

            }

            return (

                    <div>        //包裹标签

                        <h1>组件1</h1>

                        {arr}            //嵌套组件数组

                 </div>

            )

        }

    });

    var Message2 = React.createClass({

        render: function () {

            return (

                    <div>

                        <h2>组件2</h2>

                        <Message3/>     //嵌套其他组件

                    </div>

            )

        }

    });

    var Message3 = React.createClass({

        render: function () {

            return (

                    <h3>组件3</h3>

            )

        }

});

3)组件的状态state    

var Message1 = React.createClass({

        getInitialState: function () {          //react内置方法设置变量初始状态值

            return {

                clickCount: 0,

            }

        },

        handleClick: function () {

            this.setState({         //react内置方法改变变量状态

                clickCount: this.state.clickCount + 1,

            })

        },

        render: function () {

            return (

                    <div>

                        <button onClick={this.handleClick}>点击</button>

                        <p>被点击了:{this.state.clickCount}次</p>  //设置状态值显示

                    </div>

            )

        }

});

4)组件的参数:组件之间传递数据props

    var Message1 = React.createClass({

        getInitialState: function () {

            return {

                message: [

                    'test1', 'test2', 'test3'

                ]

            }

        },

        render: function () {

            return (

                    <div>

                       <Message2 message={this.state.message}/> //向组件2中传递数据

                       <h1>{title}</h1>  //此处传入的是全局变量数据,顶层数据

                    </div>

            )

        }

    });

    var title = '这是title';

    var Message2 = React.createClass({

        propTypes: {          //设置数据的类型

            message: React.PropTypes.array.isRequired

        },

        getDefaultProps: function () {    //如果没有数据,显示默认消息

            return {

                message: ['默认消息']

            }

        },

        render: function () {

            var arr = [];

            this.props.message.forEach(function (msg, i) {  //加载其他组件传递的数据

                arr.push(<li key={'key'+i}>{msg}</li>);

            })

            return (

                    <div>

                        {arr}

                    </div>

            )

        }

});

5)组件中的事件(event

    var Message1 = React.createClass({

        getInitialState: function () {

            return {

                selectV: '2',

                inputV: 'test again'

            }

        },

        handleSubmit: function () {

            console.log('submit');

        },

        handleInput: function (e) {

            this.setState({inputV: e.target.value}); //此处为react封装的事件对象

            console.log(e.nativeEvent);          //此处可以查看原生的事件对象

        },

        render: function () {

            return (

                    <form onSubmit={this.handleSubmit}>

                                   <input type="text" value={this.state.inputV} onChange={this.handleInput}/>           //添加onChange内置方法

                        <input type="text" defaultValue='default'/>  //可以修改

                        <select value={this.state.selectV}>  //如果设置value则不可修改,必须添加onChange事件,才能修改,推荐用defaultValue

                            <option value="1">1</option>

                            <option value="2">2</option>

                            <option value="3">3</option>

                        </select>

                    </form>

            )

        }

});

6)组件中元素的指向(ref

    var Message1 = React.createClass({

        getInitialState: function () {

            return {

                inputV: 'test again'

            }

        },

        handleClick: function () {

            console.log(this.refs.input.getDOMNode().value);      //获取ref=’input’的DOM元素value

            this.refs.hello.saySomething();   //调用ref=‘hello’组件的方法

        },

        console: function () {

            console.log('child')

        },

        render: function () {

            return (

                    <form onSubmit={this.handleSubmit}>

                        <input ref='input' type="text" value={this.state.inputV}/>

                        <input ref={function(comName) {  //ref可以是一个函数同时执行指向自己的方法

                            React.findDOMNode(comName).focus()

                        }} type="text" defaultValue='default'/>

                        <Child ref='hello' consoleF={this.console}/> //可以向子组件传递方法

                        <button onClick={this.handleClick} type="button">点击</button>

                    </form>

            )

        }

    });

    var Child = React.createClass({

        saySomething: function () {

            alert('hello')

        },

        render: function () {

            return (

                    <div onClick={this.props.consoleF}>

                        这是child

                    </div>

            )

        }

});

7react中的双向数据绑定

<script src="bower_components/react/react-with-addons.js"></script>        //需要引用带addon功能插件的react,js

<script src="bower_components/react/JSXTransformer.js"></script>

<script type="text/jsx">

    var Message1 = React.createClass({

        mixins: [React.addons.LinkedStateMixin],  //引入mixins插件

        getInitialState: function () {

            return {

                inputV: 'test again',

                flag: true

            }

        },

        render: function () {

            return (

                    <div>

                        <h1>{this.state.inputV}</h1>

                        <h2>这是多少? {this.state.flag ? '是1!' : '是2 '}</h2>

                        <input type="checkbox" checkedLink={this.linkState('flag') }/>  //设置绑定方法,并绑定数据

                        <input type="text" valueLink={this.linkState('inputV')}/>

                        <Child childLink={this.linkState('inputV')}/>     //可以传递绑定的方法到子组件中

                    </div>

 

            )

        }

    });

    var Child = React.createClass({

        render: function () {

            return (

                    <input valueLink={this.props.childLink}/>  //子组件接收绑定方法

            )

        }

    });

8)组件的生命周期

  组件的周期,主要分为:装载mount、更新update、卸载unmount三个过程

① 装载mount、卸载unmount

    var MessageBox = React.createClass({

        getInitialState: function () {

            console.log('getInitialState')  //打印排序1

            return {

                count: 0

            }

        },

        componentWillMount: function () { //组件将要加载时

            console.log('componentWillMount')       //打印排序2

        },

        componentDidMount: function () {  //组件已经加载完成时

            console.log('componentDidMount')        //打印排序4

        },

        componentWillUnmount: function () {    //组件将要删除时

            alert('did you want to kill me');

        },

        killComponent: function () {

            React.unmountComponentAtNode(document.getElementById('app'));     //react内置删除DOM元素的方法

        },

        render: function () {

            console.log('render')        //打印排序3

            return (

                    <div>

                        <h1>现在计数:{this.state.count}</h1>

                        <button type="button" onClick={this. killComponent}>点击</button>

                    </div>

            )

        }

    });

    React.render(<MessageBox/>,

            document.getElementById('app'),

            function () {

                console.log('渲染完成啦!!');        //打印排序5

            }

)

② 更新update

    var MessageBox = React.createClass({

        getInitialState: function () {

            console.log('getInitialState')

            return {

                count: 0

            }

        },

        shouldComponentUpdate: function (nextProp, nextState) {  //返回一个bool   

//判断是否需要更新,有两个参数,如果是组件内部数据,调用nextState,如果是父组件数据,调用nextProp

            if (nextState.count > 8) {        //如果count大于8不更新

                return false;

            }

            return true;

        },

        componentWillUpdate: function () {        //组件将要更新

            console.log('componentWillUpdate')

        },

        componentDidUpdate: function () {         //组件已经更新

            console.log('componentDidUpdate');

        },

        doUpdate: function () {

            this.setState({

                count: this.state.count + 1

            })

        },

        render: function () {

            console.log('render')

            return (

                    <div>

                        <h1>现在计数:{this.state.count}</h1>

                        <button type="button" onClick={this.doUpdate}>点击</button>

                        <Child count={this.state.count}/>

                    </div>

            )

        }

    });

    var Child = React.createClass({

        componentWillReceiveProps: function () {  //子组件将要接受props

            console.log('componentWillReceiveProps');

        },

        shouldComponentUpdate: function (nextProp, nextState) {

            if (nextProp.count > 4) {  //子组件使用nextProp中的数据判断是否更新

                return false;

            }

            return true;

        },

        render: function () {

            return (

                    <h1>现在计数:{this.props.count}</h1>

            )

        }

    });

    React.render(<MessageBox/>,

            document.getElementById('app'),

            function () {

                console.log('渲染完成啦!!');

            }

)

9)组件公用方法可以写在mixins

var stateRecordMixin = {         //定义公用的方法内容

        componentWillMount: function () {

            console.log('componentWillMount')

        },

        componentWillUpdate: function (nextProp, nextState) {

            console.log('componentWillMount')

        },

        selfFunction: function () {

            alert('selfFunction')

        }

    }

    var MessageBox = React.createClass({

        mixins: [stateRecordMixin],   //加载公用的mixin方法,数组形式

        getInitialState: function () {

            return {

                count: 0

            }

        },

        render: function () {

            return (

                    <div>

                        <button type="button" onClick={this.selfFunction}>点击</button>        //此处即可调用该公用方法中的内容

                        <Child count={this.state.count}/>

                    </div>

            )

        }

    });

    var Child = React.createClass({

        mixins: [stateRecordMixin],    //加载公用的mixin方法,数组形式

        render: function () {

            return (<div>

                        <button type="button" onClick={this.selfFunction}>点击</button>

                    </div>

            )

        }

    });

    React.render(<MessageBox/>,

            document.getElementById('app'),

            function () {

                console.log('渲染完成啦!!');

            }

    )

posted @ 2017-08-20 23:05  Tabb.Coding  阅读(212)  评论(0编辑  收藏  举报