zoukankan      html  css  js  c++  java
  • React从0到1--组件向外传递数据

    通过props向外传递数据

    在父组件ClickCounter文件里面

    constructor(props){
    super(props);
    this.onCounterUpdate = this.onCounterUpdate.bind(this);
    this.initValues = [0,10,20];

    const initSum = this.initValues.reduce((a,b)=>a+b,0);//求和
    this.state = {
    count:0,
    sum:initSum
    };

    }
    onCounterUpdate(newValue,previousValue){
    console.log(newValue,previousValue)
    const valueChange = newValue - previousValue
    this.setState({sum:this.state.sum+valueChange})
    }
    render(){
    return(
    <div>

    <Counter onUpdate = {this.onCounterUpdate} caption = "First1" initValue = {this.initValues[0]} />
    <Counter onUpdate = {this.onCounterUpdate} caption = "Second1" initValue = {this.initValues[1]} />
    <Counter onUpdate = {this.onCounterUpdate} caption = "Third1" initValue = {this.initValues[2]} />
    <div>Total Count:{this.state.sum}</div>

    </div>

    );
    }

    子组件counter文件代码
    onClickIncButton() {
    this.updateCount(true);
    }


    onClickDecButton() {
    this.updateCount(false);
    }
    updateCount(isIncrement){
    console.log(isIncrement)
    const previousValue = this.state.count;
    const newValue = isIncrement?previousValue-1:previousValue +1;
    this.setState({count:newValue})
    this.props.onUpdate(newValue,previousValue)
    }
    render() {

    const buttonStyle = {
    color: 'red'
    };
    const {caption} = this.props;
    console.log ('enter ControlPanel render ');
    return (
    <div>
    <button style={buttonStyle} onClick={this.onClickDecButton}>+</button>
    <button style={buttonStyle} onClick={this.onClickIncButton}>-</button>
    <span>{caption} count:{this.state.count}</span>
    </div>
    )
    }
  • 相关阅读:
    C语言宏的定义和宏的使用方法(#define)
    C语言字符串拼接
    OC字符串与C语言字符串之间的相互转换
    C语言#include的用法
    NSSet集合
    NSArray 数组
    预定义宏,C语言预定义的宏详解
    主流C语言编译器介绍
    无法使用此电子邮件地址。请选择其他电子邮件地址
    可变大小、颜色边框、样式的UISwitch
  • 原文地址:https://www.cnblogs.com/lk1186578324/p/9806020.html
Copyright © 2011-2022 走看看