在React

时间:2018-07-01 07:33:46

标签: javascript reactjs radio-button

如果我单击“年度”单选按钮,则应该隐藏或禁用“切换按钮”(标记为“半天”)(仅适用于“年度”单选按钮)。我该如何在React中做到这一点?

<RadioGroup onChange={this.onChange} value={this.state.leavevalue}>
    <Radio value={1}>Casual</Radio>
    <Radio value={2}>Medical</Radio>
    <Radio value={3}>Annual</Radio>
    <Radio value={4}>Lieu</Radio>
    <Radio value={5}>Special</Radio>
    <Radio value={6}>Maternity</Radio>
    <Radio value={7}>Paternity</Radio>
    <Radio value={8}>NoPay</Radio>
</RadioGroup>

这是我的切换按钮代码:

<Switch onChange={this.handleHalfDay} checked={this.state.isHalfDay} />

这是我的onChange函数:

onChange = (e) => {
    this.setState({
        leavevalue: e.target.value,
        isHalfDay: false,
    });
}

我的单选按钮和切换按钮:

radio buttons and the switch button

2 个答案:

答案 0 :(得分:3)

当您的Switch状态变量等于leavevalue时,可以禁用3

示例

class App extends React.Component {
  state = {
    leavevalue: 1,
    isHalfDay: true
  };

  handleChange = value => {
    this.setState({ leavevalue: value });
  };

  handleHalfDay = () => {
    this.setState(previousState => {
      return { isHalfDay: !previousState.isHalfDay };
    });
  };

  render() {
    return (
      <div>
        <RadioGroup
          selectedValue={this.state.leavevalue}
          onChange={this.handleChange}
        >
          <Radio value={1} />Casual
          <Radio value={2} />Medical
          <Radio value={3} />Annual
          <Radio value={4} />Lieu
          <Radio value={5} />Special
          <Radio value={6} />Maternity
          <Radio value={7} />Paternity
          <Radio value={8} />NoPay
        </RadioGroup>
        <Switch
          onChange={this.handleHalfDay}
          checked={this.state.isHalfDay}
          disabled={this.state.leavevalue === 3}
        />
      </div>
    );
  }
}

答案 1 :(得分:2)

一个简单的条件语句即可:

onChange = (e) => {
    this.setState({
      leavevalue: e.target.value,
      isHalfDay: false,
      isHalfDayHidden: e.target.value === 3
    });
  }

另一个显示或隐藏Switch的条件

{!this.state.isHalfDayHidden && (
  <Switch onChange={this.handleHalfDay} checked={this.state.isHalfDay} />
)}