tanish-kr's learning log

Learning output log

JavaScript React

stateのリフトアップ

いくつかのコンポーネントが同一の変化するデータを反映する必要がある場合、最も近い共通の祖先コンポーネントへ共有されているstateをリフトアップすることを推奨している。

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) {
    // 親コンポーネントCalculatorからtemperatureプロパティとともに渡される
    // 2. propsのonTemperatureChangeにイベントハンドラーの値を渡す
    this.props.onTemperatureChange(e.target.value);
  }

  // 6. 新しいpropsで各TemperatureInputをrenderする 
  render() {
    const temperature = this.props.temperature;
    const scale = this.props.scale;
    return (
      <fieldset>
        <legend>Enter temperature in {scaleNames[scale]}:</legend>
        {/* 1. onChangeで指定された関数をよびだす */}
        <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) {
    // 4. Calculatorコンポーネントが新しい入力値を更新した方の入力値の単位をsetStateに与えて呼び出し、
    // ReactにCalculatorコンポーネント自身を再レンダリングさせる
    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;

    // 5. 両方の入力コンポーネントの値が、現在の温度とアクティブな単位に基づいて再計算される
    // 温度の変換処理はここで行われる
    return (
      <div>
        {/* 3. どちらの入力フィールドを編集したかによってonTemperatureChangeにわたす関数が変わる */}
        <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')
);