反应函数中的if语句

时间:2020-01-29 09:15:04

标签: reactjs if-statement

我有2个具有最小和最大数字范围的输入,并且我尝试使用if语句,因此,如果用户输入的值大于最大输入的最小输入值,它将把输入重置为等于最大。为什么在minRangeInputChange函数中不起作用?

class Generator extends React.Component {
  constructor (props) {
    super(props)
    this.state = { 
      onView: '0',
      minNum: 0 ,
      maxNum: 100
    } 
  }

  btnClick = () => {
    const { minNum, maxNum } = this.state;
    const min = Math.ceil(minNum);
    const max = Math.floor(maxNum);
    const x = Math.floor(Math.random() * (max - min + 1)) + min;
    return this.setState({ onView : x });
  }

  minRangeInputChange = (event) => {
    const { minNum, maxNum } = this.state;
    if (minNum > maxNum) {
      return this.setState({ minNum: maxNum });
    } else {
      return this.setState({ minNum: event.target.value });
      console.log(minNum);
    }
  }

  maxRangeInputChange = (event) => {
    const { maxNum } = this.state;
    this.setState({ maxNum: event.target.value });
  }

  render() {
    return (
      <div className="container">
        <Instructions />
        <Range 
          max={this.state.maxNum} 
          min={this.state.minNum} 
          minChange={this.minRangeInputChange}
          maxChange={this.maxRangeInputChange}
        />
        <Generate currentClick={this.btnClick} />
        <View show={this.state.onView} />
      </div>
    );
  }
}

export default Generator;

范围组件:

class Range extends React.Component {
  constructor(props) {
     super(props)
  }

  render() {
    return (
      <div className="range">
        <h3>Minimum</h3>
        <input
          type="number" 
          value={this.props.minNum} 
          onChange={this.props.minChange} 
          required
        />
        <h3>Maximum</h3>
        <input
          type="number" 
          value={this.props.maxNum}
          onChange={this.props.maxChange}
          required
        />
      </div>
    );
  }
}

export default Range;

1 个答案:

答案 0 :(得分:1)

在函数minRangeInputChange中,您正在检查minNummaxNum,因此如果是0 > 100 then set minNum to 100。您要比较用户值与最大值,所以如果XX > max (let's say 50), then set minNum to max

您应该尝试使用此值:

  minRangeInputChange = (event) => {
    const { minNum, maxNum } = this.state;
    if (event.target.value > maxNum) {
      return this.setState({ minNum: maxNum });
    } else {
      return this.setState({ minNum: event.target.value });
    }
  }