单击按钮更改多种状态

时间:2019-03-29 14:06:12

标签: javascript reactjs setstate

在我的react应用程序中,我有一个从axios调用返回的汽车的列表,每辆汽车内部都有一个称为退款的属性,它是布尔值true或false,并且我有一个按钮和一个禁用的输入,我想如果可退款为真,则单击此按钮以启用输入;如果隐藏该输入并显示此车不退款的句子为假,则我创建的代码检查可退款是否为真,并且启用了输入,但是如果为假,则显示列表中所有汽车的假句子,这就是我正在做的事情:

初始状态:

state={cars: [],isInputDisabled: [], isVisible: true }

按钮的单击功能:

changeDisableState = (id, i) => {
    const car = this.state.cars.find(x => x.id === id);
    let isInputDisabled = this.state.isInputDisabled;
    isInputDisabled[i] = !isInputDisabled[i];
    if (car.refundable == true) {
      this.setState({ isInputDisabled });
    } else {
      this.setState({ isVisible: false });
    }
  };

渲染汽车:

renderCars() {
  const cars = this.state.cars;
  return cars.map((car, i) => (
   <div key={car.id}>
    <Button onClick={() => this.changeDisableState(car.id, i)}>Check</Button>
   {this.state.isVisible ? 
    <input
    disabled={!this.state.isInputDisabled[i]}/> : <p>Can't be refundable</p>}
   </div> 
  ));
}

3 个答案:

答案 0 :(得分:0)

似乎您的代码中缺少某些内容:

changeDisableState = (id, i) => {
    const car = this.state.cars.find(x => x.id === id);
    let isInputDisabled = this.state.isInputDisabled;
    if (car.refundable == true) {
      this.setState({ isInputDisabled[i] : !isInputDisabled[i] });
    } else {
      this.setState({ isVisible: false });
    }
  };

此行

 disabled={!this.state.isInputDisabled[i]}/>

不清楚。它显示为“如果我的isInputDisable的状态值为false,则使我的输入处于禁用状态”-不应该反感吗?

答案 1 :(得分:0)

每个汽车对象都应具有/deep/ mat-horizontal-stepper @for $i from 1 through 42 &.last-edited-step-#{$i} @for $j from 1 through $i .mat-stepper-horizontal-line:nth-of-type(#{$j}) border-color: #00c190 !important 状态。

isVisible

答案 2 :(得分:0)

您需要为最近单击的id创建另一个状态变量。然后只渲染有效ID的句子

changeDisableState = (id, i) => {
    const car = this.state.cars.find(x => x.id === id);
    let isInputDisabled = this.state.isInputDisabled;
    isInputDisabled[i] = !isInputDisabled[i];
    if (car.refundable == true) {
      this.setState({ isInputDisabled,activeid:id });
    } else {
      this.setState({ isVisible: false, activeid:id });
    }
  };


renderCars() {
  const cars = this.state.cars;
  return cars.map((car, i) => (
   <div key={car.id}>
    <Button onClick={() => this.changeDisableState(car.id, i)}>Check</Button>
   {this.state.isVisible ? 
    <input
    disabled={!this.state.isInputDisabled[i]}/> : this.state.activeid === car.id && <p>Can't be refundable</p>}
   </div> 
  ));
}