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++一个简单的手柄类模板
    矿Spring入门Demo
    [Docker] Prune Old Unused Docker Containers and Images
    [Ramda] Compose lenses
    [Docker] Build Your Own Custom Docker Image
    [SCSS] Reuse Styles with the SCSS @mixin Directive
    [Angular] Router outlet events
    [Angular] Subscribing to router events
    [Angular] Enable router tracing
  • 原文地址:https://www.cnblogs.com/lk1186578324/p/9806020.html
Copyright © 2011-2022 走看看