React和JSX

来源:互联网 发布:淘宝手机店铺怎么开通 编辑:程序博客网 时间:2024/05/20 16:14

参考:React教程

一、react概念

React 是一个用于构建用户界面的 JAVASCRIPT 库。

二、JSX概念

JSX必须借助ReactJS环境才能运行,在编写JSX代码前,必须先加载ReactJS文件,JSX并不是一门新的语言,仅仅是一个语法糖,允许开发者在javaScript中书写HTML的语法,最后每个HTML标签都转化为JavaScript代码来运行。

三、React组件

(1)、React组件

  1. React.createClass 方法用于创建一个组件类
  2. 原生 HTML 元素名以小写字母开头,而自定义的 React 类名以大写字母开头,比如 HelloMessage 不能写成 helloMessage。除此之外还需要注意组件类只能包含一个顶层标签,否则也会报错。

实例1:(封装一个输出 “Hello World!” 的组件,组件名为 HelloMessage)

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

(2)、复合组件

我们可以通过创建多个组件来合成一个组件,即把组件的不同功能点进行分离。
实例2中 WebSite 组件使用了 Name 和 Link 组件来输出对应的信息,也就是说 WebSite 拥有 Name 和 Link 的实例。

实例2:

    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(

(3)、组件API

  1. setState(object nextState[, function callback])
    合并nextState和当前state,并重新渲染组件。setState是React事件处理函数中和请求回调函数中触发UI更新的主要方法。
    nextState,将要设置的新状态,该状态会和当前的state合并
    callback,可选参数,回调函数。该函数会在setState设置成功,且组件重新渲染后调用。

  2. replaceState(object nextState[, function callback])
    nextState,将要设置的新状态,该状态会替换当前的state。
    callback,可选参数,回调函数。该函数会在replaceState设置成功,且组件重新渲染后调用
    replaceState()方法与setState()类似,但是方法只会保留nextState中状态,原state不在nextState中的状态都会被删除。

  3. 设置属性:setProps

  4. 替换属性:replaceProps

  5. 强制更新:forceUpdate

  6. 获取DOM节点:findDOMNode

  7. 判断组件挂载状态:isMounted

四、React State(状态)

  1. React 把组件看成是一个状态机(State Machines)。通过与用户的交互,实现不同状态,然后渲染 UI,让用户界面和数据保持一致。React 里,只需更新组件的 state,然后根据新的 state 重新渲染用户界面(不要操作 DOM)。
  2. 如实例1:getInitialState方法用于定义初始状态,也就是一个对象,这个对象可以通过 this.state 属性读取。每次修改后都调用render方法渲染组件。

实例1:

  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')  );

五、React Props

(1)、使用Props

  1. state 和 props 主要的区别在于 props 是不可变的,而 state 可以根据与用户交互来改变。这就是为什么有些容器组件需要定义 state 来更新和修改数据。 而子组件只能通过 props 来传递数据。
  2. 实例1中 name 属性通过 this.props.name 来获取。

实例1:

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

(2)、默认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')    );

六、组件生命周期

组件生命周期分为三个状态:

  • 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 中移除的时候立刻被调用。

实例1: (初始化 state , setNewnumber 用于更新 state。所有生命周期在 Content 组件中)

    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')    );

七、表单与事件

(1)、表单

在实例1中我们设置了输入框 input 值value = {this.state.data}。在输入框值发生变化时我们可以更新 state。我们可以使用 onChange 事件来监听 input 的变化,并修改 state。

实例1:

    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')    );

(2)、事件

实例2:(通过 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')    );

八、JSX特点

(1)、 元素名

JSX里分别使用首字母大、小写来分别区分本地组件和HTML标签,render渲染时会把大写的组件名定义为自定义的组件,把小写的组件名定义为HTML自带的标签名进行渲染。

(2)、自闭合标签

在 JSX 中, 是合法的,而 就不合法。 所有的标签都必须闭合,可以是自闭和的形式,也可以是常规的闭合。()

(3)、javaScript表达式

我们可以在 JSX 中使用 JavaScript 表达式。表达式写在花括号 {} 中

(4)、注释

注释需要写在花括号中,实例如下:

    ReactDOM.render(        <div>        <h1>菜鸟教程</h1>        {/*注释...*/}         </div>,        document.getElementById('example')    );