react组件的声明方式

2020-06-10  本文已影响0人  tenro

一: ES5写法: React.creatClass()
'老版本的使用方法,不建议使用了'

var Input = React.creatClass({
    //定义传入props中的各种类型属性
    propTypes: {
        initialValue: React.propType.string
    },
    //组件默认的props对象
    defaultProps: {
        initialValue: ''
    },
    //设置初始状态
    getInitialState: function(){
        return {
            text: this.props.initialValue || 'placeholder'
        }
    },
    //通过事件触发改变初始状态的值
    handleChange: function(event){
        this.setState({
            text: event.target.value
        });
    },
    //渲染
    render: function() {
        return (
            <div>
                  Type something:
                  <input onchange = { this.handleChange } value={this.state.text } />
            </div>
        );
    }
});

二: ES6写法

import React, { Component } from 'react'
class Input extends Component{
      constructor(props) {
          super(props);
          //设置初始状态
          this.state = {
                text: props.initialValue || 'placeholder'
          }
         //ES6类中的函数必须手动绑定
          this.handleChange = this.handleChange.bind(this)
      }
      handleChange(event) {
            this.setState({
                text: event.target.value
            });
      }
      //渲染
      render() {
            return (
                  <div>
                      Type something:
                      <input onchange = { this.handleChange } value={this.state.text } />
                  </div>
            );
      }
}

//React.Component创建的组件,函数成员不会自动绑定this, 绑定的方法有很多,除了上述的constructor中绑定this外,还可以通过箭头函数来绑定this,或使用bind(this)来绑定
箭头函数:<div onClick={ () => this.handleClick() }></div>
bind绑定:<div onclick = { this.handleClick.bind(this) }></div>
上一篇 下一篇

猜你喜欢

热点阅读