React從0到1--元件向外傳遞資料
阿新 • • 發佈:2018-11-11
通過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>
)
}