react学习笔记9--状态提升

通常情况下,同一个数据的变化需要几个不同的组件来反映,提升共享的状态到他们最近的祖先组件中。

function BoilingVerdict(props) {
    if(props.celsius >= 100) {
        return <p>the water would boil.</p>
    } else {
        return <p>this water would not boil.</p>
    }
}

//温度转换函数
function toCelsius(fahrenheit) {
    return (fahrenheit - 32) * 5 / 9;
}

function toFahrenheit(celsius) {
    return (celsius * 9 / 5) + 32;
}


//保留3位小数
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();
}

//父组件,存储state并修改state
class Calculator extends React.Component {
    constructor(props){
        super(props);
        this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
        this.handleFarenheitChange = this.handleFarenheitChange.bind(this);
        this.state = {temperature:'',scale:'c'};
    }

    handleCelsiusChange(temperature) {
        this.setState({scale:'c',temperature});
    }

    handleFarenheitChange(temperature) {
        this.setState({scale:'f',temperature});
    }


    render() {
    //得到当前的state
        const scale = this.state.scale;
        const temperature = this.state.temperature;
        //计算相应的温度
        const celsius = scale === 'f' ? tryConvert(temperature,toCelsius) : temperature;
        const fahrenheit = scale === 'c' ? tryConvert(temperature,toFahrenheit) : temperature;
        //渲染
        return (
            <div>
                <TemperatureInput 
                scale="c" 
                temperature={celsius} 
                onTemperatureChange={this.handleCelsiusChange} />
                <TemperatureInput 
                scale="f" 
                temperature={fahrenheit} 
                onTemperatureChange={this.handleFarenheitChange}/>
                <BoilingVerdict celsius={parseFloat(celsius)} />
            </div>
        );
    }
}

const scaleNames = {
    c:'celsius',
    f:'fahrenheit'
};

//接收父组件传来的属性props包括scale、temperature、onTemperatureChange
class TemperatureInput extends React.Component {
    constructor(props) {
        super(props);
        this.handleChange = this.handleChange.bind(this);
        // this.state = {temperature:''};
    }

    handleChange(e) {
        this.props.onTemperatureChange(e.target.value);
        // this.setState({temperature:e.target.value});
    }

    render() {
        const temperature = this.props.temperature;//temperature这时是父级属性,当前组件无法控制
        const scale = this.props.scale;
        return (
            <fieldset>
                <legend>enter temperature in {scaleNames[scale]}: </legend>
                    <input value={temperature} onChange={this.handleChange} />

            </fieldset>
        );
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_36926779/article/details/80985624
今日推荐