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>
)
}

猜你喜欢

转载自www.cnblogs.com/lk1186578324/p/9806020.html