React状态提升

通常, 多个组件需要反映相同的变化数据, 这时我们建议将共享状态提升到最近的共同父组件中去.

示例:

function BoilingVerdict(props) {
  if (props.celsius >= 100) {
    return 

The water would boil.

; } return

The water would not boil.

; }

接下来, 我们创建一个名为Caculator的组件. 它渲染一个用于输入温度的, 并将其值保存在this.state.temperature中. 另外, 它根据当前输入值渲染BoilingVerdict组件.

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

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

  render() {
    const temperature = this.state.temperature;
    return (
      
Enter temperature in Celsius:
); } }

在已有摄氏温度输入框的基础上, 我们提供华氏度的输入框, 并操作两个输入框的数据同步. 我们先从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 = {temperature: ''};
  }

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

  render() {
    const temperature = this.state.temperature;
    const scale = this.props.scale;
    return (
      
Enter temperature in {scaleNames[scale]}:
); } }
class Calculator extends React.Component {
  render() {
    return (
      
); } }

之后, 我们移除组件自身的state, 通过使用this.props.temperature替代this.state.temperature来读取温度数据. 当匀们想要响应数据改变时, 我们需要调用Caculator组件提供的this.props.onTemperatureChange(), 而不再使用this.setState()

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 (
      
); } }
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 (
      
Enter temperature in {scaleNames[scale]}:
); } }

 

你可能感兴趣的:(react)