React入门小册(六) 状态提升与状态共享

React 状态提升指的是将多个组件所共享的状态提升到它们的公共父组件中,以便于修改和同步这些数据的变化。一般而言,状态提升对于多个组件的功能需求相似,并且存在一定的层次结构时,是非常有用的。

在实际应用开发中,我们经常会遇到需要将数据传递给多个组件并保证数据及时更新的情境,在这种情况下,状态提升是值得考虑的解决方案之一。

接下来,我将介绍一个关于状态提升如何使用的案例:

假设我们正在开发一个包含温度计、摄氏度输入框以及华氏度输入框的组件 App。其中,当摄氏度或华氏度的值改变时,温度计会随即显示出更新后的温度。

首先,可以定义一个名为 TemperatureInput 的子组件,它包含了一个 input 元素以及 handleChange 方法:

class TemperatureInput extends React.Component {
    
    
  constructor(props) {
    
    
    super(props);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    
    
    this.props.onTemperatureChange(e.target.value, this.props.scale);
  }

  render() {
    
    
    const scaleNames = {
    
    
      c: 'Celsius',
      f: 'Fahrenheit'
    };
    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>
    );
  }
}

然后,可以在另一个名为 Calculator 的父组件中,利用状态提升将两个输入框所共享的状态(即当前输入的温度大小)提升到父组件中进行管理:

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();
}

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>
    );
  }
}

在上述代码中,Calculator 组件中存在一个 state 对象,其中包含了 scale 和 temperature 属性。当用户修改某一个输入框中的值时,会调用其对应的回调函数(handleChange),进而修改状态对象中的 temperature 值以及相关的转换结果。

通过上述示例,我们可以初步理解什么是状态提升以及其实现方式。如果你想了解更多关于状态提升的技术细节和适用场景,请查看 React 官方文档的相关章节。

猜你喜欢

转载自blog.csdn.net/weixin_42657666/article/details/129567222