React

react学习-5.React组件

2018-05-02  本文已影响31人  YINdevelop

前面的示例都是渲染的元素,主要是用来阐述ReactDOM.render()工作原理。通常在React项目中是不这样做的。我们常常会它封装到一个React组件中,然后再通过ReactDOM.render()把这个组件渲染出来。

1.什么是组件

2.React创建组件的方式

在React中创建组件有三种方式:

  1. 有状态组件(ES6写法):React.Component
  2. 有状态组件(ES5写法):React.createClass(注:此方法旧版本react可用,现已不可用
  3. 无状态组件的函数写法(函数组件)。

3.有状态?无状态?

4.React.createClass

注:React.createClass方法现已经不可用,本文章总结只是为了和es6写法作对比,从而更好的理解。

React.createClass是React刚开始创建组件的方式。这是ES5的原生的JavaScript封装的函数来实现的React组件。

动手敲个小例子

我们用一个小例子来了解一下组件的创建的机制。该例子包含一个文本框和一个按钮,单击按钮可以改变文本框的编辑状态:禁止编辑或允许编辑。并且显示自定义属性文本。

image
   var  SwitchInput = React.createClass({
        getDefaultProps : function () {
            return {myattr: "我是默认的属性"}
        }
        getInitialState:function(){
            return {enable:false}
        },
        handleClick:function(event){
            this.setState({enable:!this.state.enable})
        },
        render:function(){
            return (
                <p>
                    <input type="text" disabled={this.state.enable} />
                    <button onClick={this.handleClick}>改变textbox状态</button>
                </p>
            )
        }
    });

    ReactDOM.render(<SwitchInput myattr="我是传过来的属性"/>, document.getElementById('root'));

state:

setState()

getInitialState

props即属性(Property), 在代码中写作 props , 即可用 props 指代 properties .

getDefaultProps

render

props和state的区别

5.React.Component

ES6中类的出现改变了我们定义组件的方式,如今,React.createClass已经不可使用,新版本的react创建有状态组件都是使用React.component来创建。

我们将上面例子使用es6的方法改写下。

import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';

class SwitchInput extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      enable: true
    }
   
    this.handleClick = this.handleClick.bind(this) //绑定this
  }

  handleClick(event) {
    this.setState({
      enable: !this.state.enable
    })
  }
  render() {
      return (
       <p>
         <input type="text" disabled={this.state.enable}/>
         <button onClick={this.handleClick}>
              改变输入框编辑状态
         </button>
         自定义属性:{this.props.myattr}
       </p>
      )
  }
}
SwitchInput.defaultProps={
  myattr: "我是默认的属性" 
} 
SwitchInput.propTypes = {
  myattr: PropTypes.string
};



ReactDOM.render(<SwitchInput myattr="我是传过来的属性"/>, document.getElementById('root'));

不清楚constructor以及super等写法可以看我之前的文章。ES6学习-类(Class)的声明1

React.createClass与React.Component区别

根据上面展示代码中二者定义组件的语法格式不同之外,二者还有很多重要的区别,下面就描述一下二者的主要区别。

React.createClass创建的组件,其每一个成员函数的this都有React自动绑定,任何时候使用,直接使用this.method即可,函数中的this指向类的实例。

const Contacts = React.createClass({  
  handleClick() {
    console.log(this); // React 实例
  },
  render() {
    return (
      <div onClick={this.handleClick}></div>
    );
  }
});

React.Component创建的组件,其成员函数不会自动绑定this,需要开发者手动绑定,否则this不能获取当前组件实例对象。

class Contacts extends React.Component {  
  constructor(props) {
    super(props);
  }
  handleClick() {
    console.log(this); // null
  }
  render() {
    return (
      <div onClick={this.handleClick}></div>
    );
  }

具体绑定方法有三种:

  1. 在构造函数中绑定this.

     constructor(props) {
        super(props);
        this.handleClick = this.handleClick.bind(this); //构造函数中绑定
     }
    
  2. 直接在结构中绑定

     <div onClick={this.handleClick.bind(this)}></div> //使用bind来绑定
    
  3. 使用箭头函数绑定

     <div onClick={()=>this.handleClick()}></div> //使用arrow function来绑定
    

绑定成功后,这样在自定义函数中间就可以使用this了,若不使用this可以不绑定。

6.无状态组件

无状态组件其实是通过函数形式或者ES6 arrow function的形式创建的,它是为了创建纯展示组件。这种组件只负责根据传入的props来展示,不涉及到state状态的操作。

function HelloComponent(props) { 
  return <div>Hello {props.name}</div>
} 
 ReactDOM.render(<HelloComponent name="react" />, document.getElementById('root'))  //Hello react

react鼓励尽量使用无状态组件。其又以下几个显著特点:

下一篇——react学习-6.React组件的生命周期

上一篇 下一篇

猜你喜欢

热点阅读