iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 20
0
Modern Web

為期 30 天的 react 大冒險系列 第 20

react 大冒險-unidirectional flow 單向資料流-day 17-2

  • 分享至 

  • twitterImage
  •  

在 Calculator 中 添加兩個 method
handleCelsiusChange / handleFahrenheitChange 用來設定 Calculator 的 local state

class Calculator extends React.Component {
     constructor(props) {
         ...
         this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
         this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this);
         ...
     }
}
...
handleCelsiusChange(temp){
    this.setState({ temperature: temp , scale:'c' });
}
handleFahrenheitChange(temp){
    this.setState({ temperature: temp , scale:'f' });
}
...

將 Calculator 細拆成 TemperatureInputs
分別接收 / 顯示 兩種溫度
TemperatureInputs 顯示的內容為 Calculator pass down 的 props.temperature
onChange 時觸發 Calculator pass down 的 props.onTemperatureChange
不需要保存自己的 local state

import React from "react";

const scaleNames = {
  c: "攝氏",
  f: "華氏",
};

export default class TempInput extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
  }
  handleChange(e) {
    this.props.onTemperatureChange(e.target.value);
  }
  render() {
    const { temperature, scale } = this.props;
    return (
      <div>
        <p>輸入 {scaleNames[scale]} 溫度</p>
        <input type="number" value={temperature} onChange={this.handleChange} />
      </div>
    );
  }
}

回到 Calculator component
在 render 時得到 填入其中一種溫度,經換算後產生另種溫度的值
(ex:填入攝氏 產生華氏)
將兩種溫度值作為 TempInput 的 prop pass down

...
render() {
        const { temperature, scale } = this.state;
        const celsius = scale === 'f' ? tryConvert(temperature, toCelsius) : temperature;
        const fahrenheit = scale === 'c' ? tryConvert(temperature, toFahrenheit) : temperature;
        return (
            <div>
                <TempInput 
                    scale="c" 
                    onTemperatureChange={this.handleCelsiusChange} 
                    temperature={celsius} />
                <TempInput 
                    scale="f" 
                    onTemperatureChange={this.handleFahrenheitChange} 
                    temperature={fahrenheit} />
                <BoilingVerdict celsius={celsius} />
            </div>)
    }

最後對 TempInput 輸入值,對應的溫度就會自動產生


上一篇
react 大冒險-unidirectional flow 單向資料流-day 17-1
下一篇
react 大冒險-fetch data from API-day 18
系列文
為期 30 天的 react 大冒險30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言