react 基本应用,2

组件

**
* @Author:Rain_tdk
* @Date:2020/5/29 0029
* @version: 1.0
* @Last Modified By: Rain_tdk
* @Last Modified Time:
*/
import React, { Component } from 'react';
class Test extends Component {
//props默认值
static defaultProps={}
//props 类型校验
static propsType={}
constructor(props){
super(props);
this.state={}
}
componentWillMount() {}
componentDidMount() {}
render() {
let {active} = this.state;
return (
<div className="App">
{active}
</div>
);
}
componentWillUnmount() {}
}
export default Test;

  建议组件要包涵以上部分

  注意:

  1. defaultProps 是props 的默认值;propsType 是props 的类型检查;
  2. componentWillMount 和 componentDidMount,是react 的生命周期的方法,分别在render 之前和之后执行, 且只执行一次。
  3. 不要在componentWillMount 中使用 setState() 方法 !如果使用了setState,组件更新了state,但是组件只更新了一次,所以这是没有意义的!
  4. 轻易不要在componentDidMount 中使用 setState() 方法 !如果使用了 setState ,组件会再次更新,初始化组件的过程中就会 render 两次!
  5. 通过props 初始化 state(但是state不随着props改变而改变的时候) 时可以在 constructor() 中进行 constructor(props){ super(props); this.state={ active:props['defaultActive'] } }
  6. 组件的卸载 componentWillUnmount,一般在其中执行一些清理的方法,比如 定时器的清除、事件的回收。
  7. props是React单向数据流主要的流动管道。不允许修改值,如果要渲染一个通过props 加工而来的值 可以使用局部变量(
    1 render() {
    2         let money = this.props['price'] * this.props['qty'];
    3         return (
    4             <div className="App">
    5                 <div>总价 * {money}</div>
    6             </div>
    7         );
    8     }
    )或直接在JSX 中计算( <div>总价 * {this.props['price'] * this.props['qty']}</div> )得来

经验之谈

   props一般情况下参数。

  1. className:根节点的class,为了方便覆盖样式。
  2. onChange:当组件内部状态state 发生变化时的回调函数。
  3. default***val、***val: 默认值、当前值,方便通过内部和外部更新值。
  4. classPrefix:class 前缀

  5. props.children
    getChildren() { 
     const { panels} = this.props;
     return React.Children.map(panels, (child) => { 
     if (!child) { return; } 
     return React.cloneElement(child, {  key: '最好是个不变的不要用index', 
     }); 
     }); 
    }
    render(){
      return (<div>{this.getChildren()}</div>)  
    }
    
    或者
    render(){
      return (<div>{React.Children.map(this.props.children,(child)=>{...})}</div>)  
    }
  6. propsType: js 是弱类型语言,考虑到程序的健壮性,我是强制使用的。
  7. props 中可以传递function ,可以实现子组件向父组件的通信。 this.props.func({..params}) //子组件调用父组件传来的func 方法