react 中文文档案例七 (温度计)

Posted lolita-web

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了react 中文文档案例七 (温度计)相关的知识,希望对你有一定的参考价值。

const scaleNames = {
    c: Celsius,
    f: Fahrenheit
};
  
function toCelsius(fahrenheit) {
    return (fahrenheit - 32) * 5 / 9;
}
  
function toFahrenheit(celsius) {
    return (celsius * 9 / 5) + 32;
}
  
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 BoilingVerdict(props) {
    if (props.celsius >= 100) {
        return <p>The water would boil.</p>;
    }
    return <p>The water would not boil.</p>;
}
  
class TemperatureInput extends React.Component {
    constructor(props) {
        super(props);
        this.handleChange = this.handleChange.bind(this);
    }
  
    handleChange(e) {
        this.props.onTemperatureChange(e.target.value);
    }
  
    render() {
        const temperature = this.props.temperature;
        const scale = this.props.scale;
        return (
            <fieldset>
            <legend>Enter temperature in {scaleNames[scale]}:</legend>
            <input 
                value={temperature}
                onChange={this.handleChange} />
            </fieldset>
        );
    }
}
class Calculator extends React.Component {
    constructor(props) {
        super(props);
        this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
        this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this);
        this.state = {temperature: ‘‘, scale: c};
    }
  
    handleCelsiusChange(temperature) {
        this.setState({scale: c, temperature});
    }
  
    handleFahrenheitChange(temperature) {
        this.setState({scale: f, temperature});
    }
  
    render() {
        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.handleFahrenheitChange} />
            <BoilingVerdict
                celsius={parseFloat(celsius)} />
            </div>
        );
    }
}
  
ReactDOM.render(
    <Calculator />,
    document.getElementById(root)
);

 

以上是关于react 中文文档案例七 (温度计)的主要内容,如果未能解决你的问题,请参考以下文章

练习案例React七React结合ant design封装一个按钮组件

react 中文文档案例四 (登陆登出按钮)

react 中文文档案例六 (表单)

react 中文文档案例五 (循环列表)

React文档提升state

分享几个实用的代码片段(附代码例子)