通过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(); } 子组件counter文件代码 Total Count:{this.state.sum}
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 ({caption} count:{this.state.count}) }