admin管理员组

文章数量:1389783

I have 2 input type number fields and I'm trying to set the second field value(num2) conditionally based on the first one's(num1) value.

<input ref="num1" type="number" min="1" max="7" defaultValue={6}/>

<input ref="num2" type="number" min="0" max={this.refs.num1 === 7 ? 0 : 10} defaultValue={10}/>

I've tried the above ternary operator to set value 0 if num1's value is equal to 7. The default value for num1 is 6 and when I stepup to 7, there is no different I can see in num2.

Please help me fix this.

I have 2 input type number fields and I'm trying to set the second field value(num2) conditionally based on the first one's(num1) value.

<input ref="num1" type="number" min="1" max="7" defaultValue={6}/>

<input ref="num2" type="number" min="0" max={this.refs.num1 === 7 ? 0 : 10} defaultValue={10}/>

I've tried the above ternary operator to set value 0 if num1's value is equal to 7. The default value for num1 is 6 and when I stepup to 7, there is no different I can see in num2.

Please help me fix this.

Share Improve this question asked Nov 25, 2016 at 11:26 BodyBody 3,6889 gold badges43 silver badges51 bronze badges 1
  • For detailed investigation you have to investigate this beautifully explained documentation(masterpiece) -> reactjs/docs/lifting-state-up.html – Musa Commented Jul 9, 2018 at 20:17
Add a ment  | 

2 Answers 2

Reset to default 1

Try validating by using onChange event in the input

<input onChange={this.onChange} />

And create a method onChange with womthing like:

onChange(e) {
   let value = e.target.value;
   return validation;
}

I'm not sure if I understand what you want, but you can try something like this :

class Test extends React.Component {
    constructor(props){
      super(props);

      this.state = {
        num1: null
      }
    }

    onChange(num, e){       
        this.setState({num1: e.target.value});
    }

    render(){
        return(
            <div>
                <input type="number" min="1" max="7" defaultValue={6} value={this.state.num1} onChange={this.onChange.bind(this, "num1")}/>
                <input type="number" min="0" max={10} value={this.state.num1 == 7 ? 10 : 0} />
            </div>
        );
    }
}

React.render(<Test />, document.getElementById('container'));

Add state to your ponent and then change the value of the first input via an onChange function.

Then depending on that value show value of the second input.

Here is a fiddle.

本文标签: javascriptReactSet input number value conditionallyStack Overflow