React文档提升state

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了React文档提升state相关的知识,希望对你有一定的参考价值。

经常有些组件需要映射同一个改变的数据。我们建议将分享的state提升至最近的同一个祖先元素。我们来看看这是怎样运作的。

在这一节中,我们会创建一个温度计算器来计算提供的水温是否足够沸腾。

我们先创建一个叫BoilingVerdict的组件。它接受摄氏度温度为prop,并且打印水温是否足够沸腾:

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

下一步,我们创建一个Calculator组件。它渲染一个<input>让你输入温度,然后将温度保存在this.state.value里。

另外,它渲染BoilingVerdict通过当前输入的温度值。

class Calculator extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.state = {value: ‘‘};
  }

  handleChange(e) {
    this.setState({value: e.target.value});
  }

  render() {
    const value = this.state.value;
    return (
      <fieldset>
        <legend>Enter temperature in Celsius:</legend>
        <input
          value={value}
          onChange={this.handleChange} />
        <BoilingVerdict
          celsius={parseFloat(value)} />
      </fieldset>
    );
  }
}

在CodePen里试一试

添加第二个输入框

我们新的要求是除了摄氏度的输入之外,我们还提供一个华氏度输入框,并且它们保持同步。

我们可以先从Calculator组件里提取出TemperatureInput组件。并且添加一个新的scale prop给它,可以是“c”或者“f”。

const scaleNames = {
  c: ‘Celsius‘,
  f: ‘Fahrenheit‘
};

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

  handleChange(e) {
    this.setState({value: e.target.value});
  }

  render() {
    const value = this.state.value;
    const scale = this.props.scale;
    return (
      <fieldset>
        <legend>Enter temperature in {scaleNames[scale]}:</legend>
        <input value={value}
               onChange={this.handleChange} />
      </fieldset>
    );
  }
}

现在来修改Calculator组件来渲染两种单独的温度输入:

class Calculator extends React.Component {
  render() {
    return (
      <div>
        <TemperatureInput scale="c" />
        <TemperatureInput scale="f" />
      </div>
    );
  }
}

Try it on CodePen.

We have two inputs now, but when you enter the temperature in one of them, the other doesn‘t update. This contradicts our requirement: we want to keep them in sync.

We also can‘t display the BoilingVerdict from Calculator. The Calculator doesn‘t know the current temperature because it is hidden inside the TemperatureInput.

在CodePen里试一试。

以上是关于React文档提升state的主要内容,如果未能解决你的问题,请参考以下文章