单选按钮不调用react

时间:2019-07-11 00:49:33

标签: javascript reactjs

我已经在React程序中编写了一个简单的方法,该方法应该更改状态并更新单选按钮的指定值:

状态:

  class App extends Component {
  constructor(props) {
   super(props);
   this.state = {
   checked: [],
   expanded: [],
   keyword: "",
   protocol:"",
   time:""
   };
  }
   .
   . 
   .
  }

方法:

  handleProtocolChange = (e, {value}) =>this.setState({protocol: 
     value })
 handleTimeChange =  (e, {value}) =>this.setState({time: value })

无线电元素:

 return (
  <Form>
  <Form.Field>
  <h1 className="rct-icon-half-check2">Selected Time: <b>{this.state.time}</b></h1>
  </Form.Field>
  <Form.Field>
    <Radio
      label='Last 30 minutes'
      name='radioGroup'
      value='Last 30 minutes'
      checked={this.state.time === "Last 30 minutes"}
      onChange={this.handleTimeChange}
    />
  </Form.Field>
  <Form.Field>
    <Radio
      label='Last Hour'
      name='radioGroup'
      value='Last Hour'
      checked={this.state.time === "Last Hour"}
      onChange={this.handleTimeChange}
    />
  </Form.Field>
  <Form.Field>
    <Radio
      label='Last 8 Hours'
      name='radioGroup'
      value='Last 8 Hours'
      checked={this.state.time === "Last 8 Hours"}
      onChange={this.handleTimeChange}
    />
  </Form.Field>
  <Form.Field>
    <Radio
      label='Last 24 Hours'
      name='radioGroup'
      value='Last 24 Hours'
      checked={this.state.time === "Last 24 Hours"}
      onChange={this.handleTimeChange}
    />
  </Form.Field>

</Form>

)

但是,无论何时按下单选按钮。 setState永远不会被调用。状态会发生变化,但是按钮的选中元素却永远不会被看到:这是之前和之后的图像..检查工具中的状态变化如何但按钮未显示的提示:

我将很乐意帮助您发现问题

before pressing radio button

after pressing the radio button..state change is shown in inspector,yet no sign of change 对不起,我误会您是我早先所说的组件是设置的时间状态,这是发生相同问题的更新产品

1 个答案:

答案 0 :(得分:0)

在您的代码中,首先您可以简化功能,

handleProtocolChange = (e) => this.setState({protocol: e.target.value })
chandleTimeChange =  (e) => this.setState({time: e.target.value }) // make sure `chandleTimeChange` is not a typo

您在此处的代码有冲突,

<h1 className="rct-icon-half-check2">Selected protocol: <b>{this.state.protocol}</b></h1>

<Radio
   label='Modbus'
   name='radioGroup'
   value='Modbus'
   checked={this.props.protocol === "Modbus"}
   onChange={(this.handleProtocolChange)}
/>

在一个使用this.state.protocol的地方和另一个使用this.props.protocol的地方,请确保这不是错字。