React学习:状态提升

多个组件使用共同的状态进行变化的时候,考虑这个状态放在父组件上。

// 状态提升-
const scaleNames = {
    c: '摄氏度',
    f: '华氏度'
  };
function BoilingVerdict(props){
    if (props.celsius >=100) {
        return <div>水开了~</div>
    } else {
        return <div>还没开呢,温度太低。</div>
    }
}
class Input extends React.Component{
    constructor(props) {
        super(props);
        this.handlChange = this.handlChange.bind(this);
    }
    handlChange(e) {
        this.props.onTemperatureChange(e.target.value);
    }
    render(){
        const temperature = this.props.temperature;
        const s = this.props.s
        return (
            <fieldset>
                <legend>温度计{scaleNames[s]}</legend>
                <input value={temperature} onChange={this.handlChange}/>
            </fieldset>
        )
    }
}
function tryConvert(temperature, convert) {
    const input = parseFloat(temperature);
    if (Number.isNaN(input)) {
      return '';
    }
    const output = convert(input);
    const rounded = Math.round(output * 1000) / 1000;
    return rounded.toString();
  }
  function toCelsius(fahrenheit) {
    return (fahrenheit - 32) * 5 / 9;
  }
  
  function toFahrenheit(celsius) {
    return (celsius * 9 / 5) + 32;
  }
class Calculator extends React.Component{
    constructor(props){
        super(props);
        this.handlChangeCelsius = this.handlChangeCelsius.bind(this);
        this.handlChangeFahrenheit = this.handlChangeFahrenheit.bind(this);
        this.state = {
            temperature:"",
            s:"c"
        }
    }
    handlChangeCelsius(temperature) {
        this.setState({
            temperature:temperature,
            s:"c"
        })
    }
    handlChangeFahrenheit(temperature) {
        this.setState({
            temperature:temperature,
            s:"f"
        })
    }
    render(){
        const celsius = this.state.s ==='c'?this.state.temperature:tryConvert(this.state.temperature,toCelsius);
        const fahrenheit = this.state.s ==='f'?this.state.temperature:tryConvert(this.state.temperature,toFahrenheit);
        return (
           <div>
                <Input s="c" temperature={celsius} onTemperatureChange={this.handlChangeCelsius}></Input>
                <Input s="f" temperature={fahrenheit} onTemperatureChange={this.handlChangeFahrenheit}></Input>
                <BoilingVerdict celsius={Number(celsius)}/>
           </div>
        )
    }
}

可变数据应保证只有一个数据源,如果两个组件需要相同的state,应该把它提升到相同的父组件中,所有改变也是通过父组件去改,子组件书写  this.props.父组件方法(参数),父组件写:<子组件  子组件调用方法名={func}>。

该章节在我的理解中应该是在介绍子组件和父组件的通信。

 
posted @ 2019-09-28 11:11  前端小可爱  阅读(177)  评论(0编辑  收藏  举报