react开发中的小细节

  目前开始使用react余遇到的问题还不是很多,但还是希望总结一下。

  react中的属性prop

    在react中组件的父子组件的通信是基于prop的,当然对于底层的东西不是特别了解,但可以说一说它的基本用法。

    上代码:

import React, { Component, PropTypes} from 'react'

class Parent Component { //父组件
  render() {
    return (
      <div>
        <Children name='刘恒'></Children>
      </div>
    )
  }
}
class Children extends Component {  //子组件
    reder() {
        return(
            <div>{this.prop.name}</div>
        )
    }
} 

Children.propTypes ={ //验证父组件传到子组件的属性是否为字符串
  name : PropTypes.string.isRequired
}
<!-- 他们之间通过prop传递数据,当然这是单向的,也无法双向,父组件控制子组件 当然可以更加深入,也可以通过点击事件控制 -->

    点击事件通过prop控制就不在这里上代码了,尽量将组件细化,当然你也可以不细化,这取决你的业务功能。同时在使用必须验证prop的类型是否正确

  react中的属性state

    state是react中的状态,非常重要

import React, { Component } from 'react'

class Messages extends Component {
  constructor(){
    super();
    this.state({
        item: 0
    })
  }
  AddClick(event, item) {
    const i = this.state.item;
    i++;
    this.setState({
        item: i
    })
    console.log(item)
  }
  render() {
    return (
      <div>
        <h2 onClick={(event) => {this.AddClick(event,this.state.item)}}>{this.state.item}</h2>
      </div>
    )
  }

<!-- 这段代码中有两个需要注意的问题 -->
  1.  在创建类组件初始化时,Es6中的做法是使用constructor构造函数初始化。
  2.  在点击中,你要获取绑定在元素中的值时,需要记住,必须使用箭头函数闭包调用,不然无法获取到 this.state.item 的值
原文地址:https://www.cnblogs.com/liuheng/p/6581491.html