react状态提升
https://zh-hans.reactjs.org/docs/lifting-state-up.html
这样 多个子组件的值可以联动变化。
关键点:
class ParentComponent extends React.Componnet{
// ………… changeMyValue=(para)=>{ this.setState({myValue: para}) } render(){ return( <SubComponent myValue=`${this.state.myValue}` changeMyValue=changeMyValue> ) } }
class SubComponent extends React.Componnet{ // ………… constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); } handleChange(e) { this.props.changeMyValue(e.target.value); } render(){ const myValue = this.props.myValue; return( <Input value=`${myValue}` onChange={this.handleChange} /> ) } }
1.子组件通过父组件传递过来的prop设置子组件的值。
2.子组件更新值得时候,通过父组件prop传递过来的方法changeMyValue,修改父组件用于传递给子组件的值。
下面是官方例子:
1 class TemperatureInput extends React.Component { 2 constructor(props) { 3 super(props); 4 this.handleChange = this.handleChange.bind(this); 5 } 6 7 handleChange(e) { 8 this.props.onTemperatureChange(e.target.value); 9 } 10 11 render() { 12 const temperature = this.props.temperature; 13 const scale = this.props.scale; 14 return ( 15 <fieldset> 16 <legend>Enter temperature in {scaleNames[scale]}:</legend> 17 <input value={temperature} 18 onChange={this.handleChange} /> 19 </fieldset> 20 ); 21 } 22 }
1 class Calculator extends React.Component { 2 constructor(props) { 3 super(props); 4 this.handleCelsiusChange = this.handleCelsiusChange.bind(this); 5 this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this); 6 this.state = {temperature: '', scale: 'c'}; 7 } 8 9 handleCelsiusChange(temperature) { 10 this.setState({scale: 'c', temperature}); 11 } 12 13 handleFahrenheitChange(temperature) { 14 this.setState({scale: 'f', temperature}); 15 } 16 17 render() { 18 const scale = this.state.scale; 19 const temperature = this.state.temperature; 20 const celsius = scale === 'f' ? tryConvert(temperature, toCelsius) : temperature; 21 const fahrenheit = scale === 'c' ? tryConvert(temperature, toFahrenheit) : temperature; 22 23 return ( 24 <div> 25 <TemperatureInput 26 scale="c" 27 temperature={celsius} 28 onTemperatureChange={this.handleCelsiusChange} /> 29 <TemperatureInput 30 scale="f" 31 temperature={fahrenheit} 32 onTemperatureChange={this.handleFahrenheitChange} /> 33 <BoilingVerdict 34 celsius={parseFloat(celsius)} /> 35 </div> 36 ); 37 } 38 }