React单选按钮没有设置初始值;仅后续值

时间:2017-12-06 18:29:02

标签: javascript reactjs

我有一个包含4个无线电输入的表格。我希望使用已检查输入的值更新组件状态。

目前输入是检查值后面的一个值(即直到第二次点击才开始正确更新状态)。

如何在第一次点击时设置状态?

component.js

import React, { Component } from 'react';

class Graph extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      option: null
    };
  }

  setOption(value) {
    this.setState({option: value});
  }

  render() {
    return (
      <form>
        <input
        type="radio"
        name="option"
        onChange={(e) => this.setOption('tmax_C')}
        checked={ this.state.option === 'tmax_C' }
        value="tmax_C" />
        <label htmlFor="option">Max Temp.</label>

        <input type="radio"
        name="option"
        onChange={(e) => this.setOption('tmin_C')}
        checked={ this.state.option === 'tmin_C' }
        value="tmin_C" />
        <label htmlFor="option">Min Temp</label>

        <input type="radio"
        name="option"
        onChange={(e) => this.setOption('rain_mm')}
        checked={ this.state.option === 'rain_mm' }
        value="rain_mm" />
        <label htmlFor="option">Rain mm</label>

        <input type="radio"
        name="option"
        onChange={(e) => this.setOption('sunshine_hours')}
        checked={ this.state.option === 'sunshine_hours' }
        value="sunshine_hours" />
        <label htmlFor="option">Sunshine Hours</label>
      </form>
    );
  }
}

export default Graph;

1 个答案:

答案 0 :(得分:0)

设置组件状态是异步的。使用函数将立即更新组件:this.setState(() => ({option: value}));

更多信息:react setState docs

根据问题的第二部分:使处理程序更具功能的另一种方法是返回一个设置传递值的处理程序:

&#13;
&#13;
import React, { Component } from 'react';

class Graph extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      option: null
    };
  }

  setOption = (value) =>
    this.setState(() => {
      return { option: value };
    });


  render() {
    return (
      <form>
        <input
        type="radio"
        name="option"
        onChange={this.setOption('tmax_C')}
        checked={ this.state.option === 'tmax_C' }
        value="tmax_C" />
        <label htmlFor="option">Max Temp.</label>

        <input type="radio"
        name="option"
        onChange={this.setOption('tmin_C')}
        checked={ this.state.option === 'tmin_C' }
        value="tmin_C" />
        <label htmlFor="option">Min Temp</label>

        <input type="radio"
        name="option"
        onChange={this.setOption('rain_mm')}
        checked={ this.state.option === 'rain_mm' }
        value="rain_mm" />
        <label htmlFor="option">Rain mm</label>

        <input type="radio"
        name="option"
        onChange={this.setOption('sunshine_hours')}
        checked={ this.state.option === 'sunshine_hours' }
        value="sunshine_hours" />
        <label htmlFor="option">Sunshine Hours</label>
      </form>
    );
  }
}

export default Graph;
&#13;
&#13;
&#13;