[React]1:基本语法练习

来源:互联网 发布:软件测试工作分类 编辑:程序博客网 时间:2024/05/16 23:42

原文地址:http://www.ruanyifeng.com/blog/2015/03/react.html


/** * Created by liyanq on 17/2/28. */import React from 'react'var ReactROM = require("react-dom");ReactROM.render(<h1>Hello World</h1>, window.document.getElementById("example"));var arr = [<span style={{color: "red"}}>one</span>, "two", "three"];//这也行~~~ReactROM.render(    <div>        {arr.map(function (name) {            return <div key={name}>hello,{name}</div>        })}    </div>, window.document.getElementById("arr"));/** * 组件类的第一个字母必须大写,否则会报错。 * 组件类只能包含一个顶层标签,否则也会报错。 * */var HelloC1 = React.createClass({    render: function () {        return <h3>我是HelloC1类,内容:{this.props.name}</h3>    }});ReactROM.render(<HelloC1 name="HelloC1值"/>, window.document.getElementById("c1"));/** * this.props.children 的值有三种可能: * 如果当前组件没有子节点,它就是 undefined ; * 如果有一个子节点,数据类型是 object ; * 如果有多个子节点,数据类型就是 array * */var HelloC2 = React.createClass({    render: function () {        return (            <ul>                {React.Children.map(this.props.children, function (item) {                    return <li>{item}</li>                })}            </ul>        )    }});ReactROM.render(    <HelloC2>        <span>HelloC2值1</span>        <span>HelloC2值2</span>    </HelloC2>, window.document.getElementById("c2"));/** * 组件的属性可以接受任意值,字符串、对象、函数等等都可以。 * */var HelloC3 = React.createClass({    getDefaultProps: function () {        return {            defTitle: "MrLi"        }    },    propTypes: {        title: React.PropTypes.string.isRequired    },    render: function () {        return <h3>HelloC3:{this.props.title};默认属性:{this.props.defTitle}</h3>    }});var d = 123;//EM环境可以使用toString()转换~ReactROM.render(<HelloC3 title={d.toString()}/>, window.document.getElementById("c3"));/** * 组件并不是真实的 DOM 节点,而是存在于内存之中的一种数据结构,叫做虚拟 DOM (virtual DOM)。 * 只有当它插入文档以后,才会变成真实的 DOM 。 * 根据 React 的设计,所有的 DOM 变动,都先在虚拟 DOM 上发生,然后再将实际发生变动的部分,反映在真实 DOM上, * 这种算法叫做 DOM diff ,它可以极大提高网页的性能表现。 * 但是,有时需要从组件获取真实 DOM 的节点,这时就要用到 ref 属性 */var HelloC4 = React.createClass({    handleClick: function (event) {        this.refs["myTextInput"].focus();        console.log(event);        alert(this.refs["myTextInput"].value);        event.stopPropagation();        event.preventDefault();    },    render: function () {        return (            <div>                <input type="text" ref="myTextInput"/>                <button onClick={this.handleClick}>点击弹窗</button>            </div>)    }});ReactROM.render(<HelloC4/>, window.document.getElementById("c4"));/** * React 的一大创新,就是将组件看成是一个状态机, * 一开始有一个初始状态,然后用户互动,导致状态变化,从而触发重新渲染 UI. * this.setState 方法就修改状态值,每次修改以后,自动调用 this.render 方法,再次渲染组件. * this.props 表示那些一旦定义,就不再改变的特性,而 this.state 是会随着用户互动而产生变化的特性。 * */var HelloC5 = React.createClass({    handleClick: function (event) {        this.setState({liked: !this.state.liked})    },    getInitialState: function () {        return {liked: false};    },    render: function () {        var text = this.state.liked ? "liked" : "have\'t liked";        return (            <div onClick={this.handleClick}>                You{text} this.click to toggle;            </div>        );    }});ReactROM.render(<HelloC5/>, window.document.getElementById("c5"));/** * 文本输入框的值,不能用 this.props.value 读取,而要定义一个 onChange 事件的回调函数. * 通过 event.target.value 读取用户输入的值。 * textarea 元素、select元素、radio元素都属于这种情况 * */var HelloC6 = React.createClass({    handleChange: function (event) {        this.setState({inputValue: event.target.value})    },    getInitialState: function () {        return {inputValue: "hello"}    },    render: function () {        return (            <div>                <input type="text" value={this.state.inputValue} onChange={this.handleChange}/>                <h3>{this.state.inputValue}</h3>            </div>        )    }});ReactROM.render(<HelloC6/>, window.document.getElementById("c6"));/** * Mounting:已插入真实 DOM * Updating:正在被重新渲染 * Unmounting:已移出真实 DOM * React 组件样式是一个对象,所以第一重大括号表示这是 JavaScript 语法,第二重大括号表示样式对象。 * */var HelloC7 = React.createClass({    componentWillMount: function () {        console.log("componentWillMount");    },    componentDidMount: function () {        console.log("componentDidMount");        this.time = setInterval(function () {            var opacity = this.state.opacity;            var count = this.state.count;            opacity -= 0.2;            if (opacity < 0.1) {                count++;                opacity = 1.0;            }            this.setState({opacity: opacity, count: count});        }.bind(this), 100)    },    componentWillUpdate: function () {        console.log("componentWillUpdate");    },    componentDidUpdate: function () {        console.log("componentDidUpdate");    },    componentWillUnmount: function () {        console.log("componentWillUnmount");    },    componentWillReceiveProps: function () {        console.log("componentWillReceiveProps");    },    render: function () {        return (            <div style={{opacity: this.state.opacity}}>                <h3>Hello,{this.props.name}</h3>            </div>        )    },    getInitialState: function () {        return {opacity: 1.0, count: 0}    },    shouldComponentUpdate: function (nextProps, nextState) {        return nextState.count < 2;    }});ReactROM.render(<HelloC7 name="World"/>, window.document.getElementById("c7"));/** * 添加jquery分两步,1:添加扩展库,2:在index.html中加入jquery引用。 * 组件的数据来源,通常是通过 Ajax 请求从服务器获取,可以使用 componentDidMount 方法设置 Ajax 请求, * 等到请求成功,再用 this.setState 方法重新渲染 UI * */var HelloC8 = React.createClass({    getInitialState: function () {        return {userName: ""}    },    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 (            <di>                {this.state.userName}'s last gist is                <a href={this.state.lastGistUrl}>here</a>            </di>        )    }});ReactROM.render(<HelloC8 source="https://api.github.com/users/octocat/gists"/>,    window.document.getElementById("c8"));var HelloC9 = React.createClass({    getInitialState: function () {        return {loading: true, error: null, data: null}    },    componentDidMount: function () {        this.props.promise.then(            value=>this.setState({loading: false, data: value}),            function (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 message:{this.state.error}</span>)        }        else {            var items = this.state.data["items"];            var repoList = items.map(function (item) {                return (                    <li key={item["name"]}>                        <a href={item["html_url"]}>{item["name"]}</a>({item["stargazers_count"]}stars)<br/>                        {item["description"]}                    </li>                )            });            return (                <div>                    <h1>Most Popular JavaScript Projects in Github</h1>                    <ol>{repoList}</ol>                </div>)        }    }});ReactROM.render(    <HelloC9        promise={$.getJSON("https://api.github.com/search/repositories?q=javascript&sort=stars")}/>,    window.document.getElementById("c9"));


0 0
原创粉丝点击