React

来源:互联网 发布:淘宝简易射影棚 编辑:程序博客网 时间:2024/06/15 09:34

1.安装

<script src="https://cdn.bootcss.com/react/15.4.2/react.min.js"></script> // React 的核心库<script src="https://cdn.bootcss.com/react/15.4.2/react-dom.min.js"></script> // 提供与 DOM 相关的功能<script src="https://cdn.bootcss.com/babel-standalone/6.22.1/babel.min.js"></script> // Babel 可以将 ES6 代码转为 ES5 代码

2.基本语法

<div id="example"></div><script type="text/babel">    ReactDOM.render(        <h1>Hello, world!</h1>,        document.getElementById('example')    );</script>

3.使用 create-react-app 快速构建 React 开发环境

$ npm install -g create-react-app$ create-react-app my-app$ cd my-app/$ npm start

在浏览器中打开 http://localhost:3000/ 可看到效果

4.JSX
多个元素,需要一个div嵌套,添加data-属性

ReactDOM.render(    <div>    <h1>菜鸟教程</h1>    <h2>欢迎学习 React</h2>    <p data-myattribute = "somevalue">这是一个很不错的 JavaScript 库!</p>    </div>    ,    document.getElementById('example'));

独立文件

<script type="text/babel" src="helloworld_react.js"></script>

JavaScript 表达式

ReactDOM.render(    <div>      <h1>{1+1}</h1>    </div>    ,    document.getElementById('example'));

不能使用 if else 语句,但可以使用 conditional (三元运算) 表达式来替代

ReactDOM.render(    <div>      <h1>{i == 1 ? 'True!' : 'False'}</h1>    </div>    ,    document.getElementById('example'));

使用内联样式,不必带px后缀

var myStyle = {    fontSize: 100,    color: '#FF0000'};ReactDOM.render(    <h1 style = {myStyle}>菜鸟教程</h1>,    document.getElementById('example'));

注释
在标签内部的注释需要花括号
在标签外的的注释不能使用花括号

ReactDOM.render(    /*注释 */    <h1>孙朝阳 {/*注释*/}</h1>,    document.getElementById('example'));

数组
JSX 在模板中插入数组会自动展开所有成员

var arr = [  <h1>菜鸟教程</h1>,  <h2>学的不仅是技术,更是梦想!</h2>,];ReactDOM.render(  <div>{arr}</div>,  document.getElementById('example'));

渲染 HTML 标签或 React 组件
渲染HTML 标签,只需在 JSX 里使用小写字母的标签名

var myDivElement = <div className="foo" />;ReactDOM.render(myDivElement, document.getElementById('example'));

渲染 React 组件,只需创建一个大写字母开头的本地变量

var MyComponent = React.createClass({/*...*/});var myElement = <MyComponent someProperty={true} />;ReactDOM.render(myElement, document.getElementById('example'));

由于 JSX 就是 JavaScript,一些标识符像 class 和 for 不建议作为 XML 属性名(class 和 for 是 JavaScript 的保留字)。作为替代,React DOM 使用 className 和 htmlFor 来做对应的属性。

5.React 组件

var HelloMessage = React.createClass({  render: function() {    return <h1>Hello World!</h1>;  }});ReactDOM.render(  <HelloMessage />,  document.getElementById('example'));

React.createClass 方法用于生成一个组件类 HelloMessage。
<HelloMessage />实例组件类并输出信息。

向组件传递参数用 this.props 对象

var HelloMessage = React.createClass({  render: function() {    return <h1>Hello {this.props.name}</h1>;  }});ReactDOM.render(  <HelloMessage name="Runoob" />,  document.getElementById('example'));

复合组件

var WebSite = React.createClass({  render: function() {    return (      <div>        <Name name={this.props.name} />        <Link site={this.props.site} />      </div>    );  }});var Name = React.createClass({  render: function() {    return (      <h1>{this.props.name}</h1>    );  }});var Link = React.createClass({  render: function() {    return (      <a href={this.props.site}>        {this.props.site}      </a>    );  }});ReactDOM.render(  <WebSite name="菜鸟教程" site=" http://www.runoob.com" />,  document.getElementById('example'));6.React State(状态)var LikeButton = React.createClass({    getInitialState: function() {        return {liked: false};    },    handleClick: function(event) {        this.setState({liked: !this.state.liked});    },    render: function() {        var text = this.state.liked ? '喜欢' : '不喜欢';        return (            <p onClick={this.handleClick}>                你<b>{text}</b>我。点我切换状态。            </p>        );    }});ReactDOM.render(    <LikeButton />,    document.getElementById('example'));

创建 LikeButton 组件,getInitialState 方法用于定义初始状态,也就是一个对象,这个对象可以通过 this.state 属性读取。当用户点击组件,导致状态变化,this.setState 方法就修改状态值,每次修改以后,自动调用 this.render 方法,再次渲染组件。
7.React Props(与 state 主要的区别在于 props 是不可变的,而 state 可以根据与用户交互来改变)

var HelloMessage = React.createClass({    render: function() {        return <h1>Hello {this.props.name}</h1>;    }});ReactDOM.render(    <HelloMessage name="Runoob" />,    document.getElementById('example'));默认 Props(getDefaultProps() 方法为 props 设置默认值)var HelloMessage = React.createClass({  getDefaultProps: function() {    return {      name: 'Runoob'    };  },  render: function() {    return <h1>Hello {this.props.name}</h1>;  }});ReactDOM.render(  <HelloMessage />,  document.getElementById('example'));

在父组件中设置 state, 并通过在子组件上使用 props 将其传递到子组件上

var WebSite = React.createClass({  getInitialState: function() {    return {      name: "菜鸟教程",      site: "http://www.runoob.com"    };  },  render: function() {    return (      <div>        <Name name={this.state.name} />        <Link site={this.state.site} />      </div>    );  }});var Name = React.createClass({  render: function() {    return (      <h1>{this.props.name}</h1>    );  }});var Link = React.createClass({  render: function() {    return (      <a href={this.props.site}>        {this.props.site}      </a>    );  }});ReactDOM.render(  <WebSite />,  document.getElementById('example'));Props 验证Props 验证使用 propTypesvar title = "菜鸟教程";// var title = 123;var MyTitle = React.createClass({  propTypes: {    title: React.PropTypes.string.isRequired,  },  render: function() {     return <h1> {this.props.title} </h1>;   }});ReactDOM.render(    <MyTitle title={title} />,    document.getElementById('example'));

更多验证器

React.createClass({  propTypes: {    // 可以声明 prop 为指定的 JS 基本数据类型,默认情况,这些数据是可选的   optionalArray: React.PropTypes.array,    optionalBool: React.PropTypes.bool,    optionalFunc: React.PropTypes.func,    optionalNumber: React.PropTypes.number,    optionalObject: React.PropTypes.object,    optionalString: React.PropTypes.string,    // 可以被渲染的对象 numbers, strings, elements 或 array    optionalNode: React.PropTypes.node,    //  React 元素    optionalElement: React.PropTypes.element,    // 用 JS 的 instanceof 操作符声明 prop 为类的实例。    optionalMessage: React.PropTypes.instanceOf(Message),    // 用 enum 来限制 prop 只接受指定的值。    optionalEnum: React.PropTypes.oneOf(['News', 'Photos']),    // 可以是多个对象类型中的一个    optionalUnion: React.PropTypes.oneOfType([      React.PropTypes.string,      React.PropTypes.number,      React.PropTypes.instanceOf(Message)    ]),    // 指定类型组成的数组    optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number),    // 指定类型的属性构成的对象    optionalObjectOf: React.PropTypes.objectOf(React.PropTypes.number),    // 特定 shape 参数的对象    optionalObjectWithShape: React.PropTypes.shape({      color: React.PropTypes.string,      fontSize: React.PropTypes.number    }),    // 任意类型加上 `isRequired` 来使 prop 不可空。    requiredFunc: React.PropTypes.func.isRequired,    // 不可空的任意类型    requiredAny: React.PropTypes.any.isRequired,    // 自定义验证器。如果验证失败需要返回一个 Error 对象。不要直接使用 `console.warn` 或抛异常,因为这样 `oneOfType` 会失效。    customProp: function(props, propName, componentName) {      if (!/matchme/.test(props[propName])) {        return new Error('Validation failed!');      }    }  },  /* ... */});

8.React 组件 API

设置状态:setState(setState()并不会立即改变this.state,而是创建一个即将处理的state。setState()并不一定是同步的,为了提升性能React会批量执行state和DOM渲染。

var Counter = React.createClass({  getInitialState: function () {    return { clickCount: 0 };  },  handleClick: function () {    this.setState(function(state) {      return {clickCount: state.clickCount + 1};    });  },  render: function () {    return (<h2 onClick={this.handleClick}>点我!点击次数为: {this.state.clickCount}</h2>);  }});ReactDOM.render(  <Counter />,  document.getElementById('message'));

替换状态:replaceState
replaceState()方法与setState()类似,但是方法只会保留nextState中状态,原state不在nextState中的状态都会被删除。

设置属性:setProps

替换属性:replaceProps
replaceProps()方法与setProps类似,但它会删除原有props

强制更新:forceUpdate
forceUpdate()方法会使组件调用自身的render()方法重新渲染组件,组件的子组件也会调用自己的render()。但是,组件重新渲染时,依然会读取this.props和this.state,如果状态没有改变,那么React只会更新DOM。
forceUpdate()方法适用于this.props和this.state之外的组件重绘(如:修改了this.state后),通过该方法通知React需要调用render()
一般来说,应该尽量避免使用forceUpdate(),而仅从this.props和this.state中读取状态并由React触发render()调用。

获取DOM节点:findDOMNode

判断组件挂载状态:isMounted
可以使用该方法保证了setState()和forceUpdate()在异步场景下的调用不会出错。

9.React 组件生命周期

组件的生命周期可分成三个状态:
Mounting:已插入真实 DOM
Updating:正在被重新渲染
Unmounting:已移出真实 DOM

生命周期的方法有:
componentWillMount 在渲染前调用,在客户端也在服务端。
componentDidMount : 在第一次渲染后调用,只在客户端。之后组件已经生成了对应的DOM结构,可以通过this.getDOMNode()来进行访问。 如果你想和其他JavaScript框架一起使用,可以在这个方法中调用setTimeout, setInterval或者发送AJAX请求等操作(防止异部操作阻塞UI)。
componentWillReceiveProps 在组件接收到一个新的prop时被调用。这个方法在初始化render时不会被调用。
shouldComponentUpdate 返回一个布尔值。在组件接收到新的props或者state时被调用。在初始化时或者使用forceUpdate时不被调用。
可以在你确认不需要更新组件时使用。
componentWillUpdate在组件接收到新的props或者state但还没有render时被调用。在初始化时不会被调用。
componentDidUpdate 在组件完成更新后立即调用。在初始化时不会被调用。
componentWillUnmount在组件从 DOM 中移除的时候立刻被调用。

var Hello = React.createClass({  getInitialState: function () {    return {      opacity: 1.0    };  },  componentDidMount: 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);var Button = React.createClass({  getInitialState: function() {    return {      data:0    };  },  setNewNumber: function() {    this.setState({data: this.state.data + 1})  },  render: function () {      return (         <div>            <button onClick = {this.setNewNumber}>INCREMENT</button>            <Content myNumber = {this.state.data}></Content>         </div>      );    }})var Content = React.createClass({  componentWillMount:function() {      console.log('Component WILL MOUNT!')  },  componentDidMount:function() {       console.log('Component DID MOUNT!')  },  componentWillReceiveProps:function(newProps) {        console.log('Component WILL RECEIVE PROPS!')  },  shouldComponentUpdate:function(newProps, newState) {        return true;  },  componentWillUpdate:function(nextProps, nextState) {        console.log('Component WILL UPDATE!');  },  componentDidUpdate:function(prevProps, prevState) {        console.log('Component DID UPDATE!')  },  componentWillUnmount:function() {         console.log('Component WILL UNMOUNT!')  },    render: function () {      return (        <div>          <h3>{this.props.myNumber}</h3>        </div>      );    }});ReactDOM.render(   <div>      <Button />   </div>,  document.getElementById('example'));

10.React AJAX

var UserGist = React.createClass({    getInitialState: function() {        return {            username: '',            lastGistUrl: ''        };    },    componentDidMount: function() {        this.serverRequest = $.get(this.props.source, function (result) {            var lastGist = result[0];            this.setState({                username: lastGist.owner.login,                lastGistUrl: lastGist.html_url            });        }.bind(this));    },    componentWillUnmount: function() {        this.serverRequest.abort();    },    render: function() {        return (            <div>                {this.state.username} 用户最新的 Gist 共享地址:                <a href={this.state.lastGistUrl}>{this.state.lastGistUrl}</a>            </div>        );    }});ReactDOM.render(    <UserGist source="https://api.github.com/users/octocat/gists" />,    document.getElementById('example'));

React 组件的数据可以通过 componentDidMount 方法中的 Ajax 来获取(上例中使用了jquery的ajax),当从服务端获取数据库可以将数据存储在 state 中,再用 this.setState 方法重新渲染 UI。
当使用异步加载数据时,在组件卸载前使用 componentWillUnmount 来取消未完成的请求。
11.React 表单

设置输入框 input 值value = {this.state.data},使用 onChange 事件来监听 input 的变化,修改 state

var HelloMessage = React.createClass({  getInitialState: function() {    return {value: 'Hello Runoob!'};  },  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} />             <h4>{value}</h4>           </div>;  }});ReactDOM.render(  <HelloMessage />,  document.getElementById('example'));

12.React 事件

onClick 事件

var HelloMessage = React.createClass({  getInitialState: function() {    return {value: 'Hello Runoob!'};  },  handleChange: function(event) {    this.setState({value: '菜鸟教程'})  },  render: function() {    var value = this.state.value;    return <div>            <button onClick={this.handleChange}>点我</button>            <h4>{value}</h4>           </div>;  }});ReactDOM.render(  <HelloMessage />,  document.getElementById('example'));复用组件var Content = React.createClass({  render: function() {    return  <div>              <button onClick = {this.props.updateStateProp}>点我</button>              <h4>{this.props.myDataProp}</h4>           </div>  }});var HelloMessage = React.createClass({  getInitialState: function() {    return {value: 'Hello Runoob!'};  },  handleChange: function(event) {    this.setState({value: '菜鸟教程'})  },  render: function() {    var value = this.state.value;    return <div>            <Content myDataProp = {value}               updateStateProp = {this.handleChange}></Content>           </div>;  }});ReactDOM.render(  <HelloMessage />,  document.getElementById('example'));

13.React Refs

var MyComponent = React.createClass({  handleClick: function() {    // 使用原生的 DOM API 获取焦点    this.refs.myInput.focus();  },  render: function() {    //  当组件插入到 DOM 后,ref 属性添加一个组件的引用于到 this.refs    return (      <div>        <input type="text" ref="myInput" />        <input          type="button"          value="点我输入框获取焦点"          onClick={this.handleClick}        />      </div>    );  }});ReactDOM.render(  <MyComponent />,  document.getElementById('example'));