Reputation: 33
I have 3 inputs and need by entering value in first input two others recalculate their values each time when I change value in first input. X - should be entered by user, y = X * X, z = X / 2
<label>X</label>
<input value={x} onChange={this.handleChange} />
<label>Y</label>
<input value={y} onChange={this.handleChange} />
<label>Z</label>
<input value={z} onChange={this.handleChange} />
Upvotes: 1
Views: 59
Reputation: 579
you can use state, it helps you to render your ui whenever you need
<label>X</label>
<input value={this.state.x} onChange={(input)=>this.setState(X:input)} />
<label>Y</label>
<input value={this.state.y} onChange={(input)=>this.setState(y:input)} />
<label>Z</label>
<input value={this.state.z} onChange={(input)=>this.setState(z:input)} />
or
constructor(props) {
super(props);
this.state = {
y: 0,
y: 0,
z: 0,
};
this.onPress = this.onPress.bind(this);
}
and then use onpress function like this:
onPress={(input) => this.onPress(input)}
Upvotes: 0
Reputation: 3428
Welcome to React
World. You need to use one state
value to save x
value.
state={
x: 0,
}
handleChange = (e) => {
this.setState({ x: e.target.value});
}
...
render() {
const { x } = this.state;
...
<label>X</label>
<input value={x} onChange={this.handleChange} />
<label>Y</label>
<input value={x * x} readOnly} />
<label>Z</label>
<input value={x / 2} readOnly} />
}
If you update the first input
value, that value will be saved in x
state value. That makes rerender
your component.
According to your question How to bind 3 inputs values?,
If you need to bind multiple input
changes with one function, you can pass unique Id to handleChange
function.
handleChange = (e, inputId) => {
if (inputId === 0) {
this.setState({ x: e.target.value });
} else if(inputId === 1) {
this.setState({ y: e.target.value });
} else if(inputId === 2) {
this.setState({ z: e.target.value });
}
}
...
<input value={x} onChange={() => this.handleChange(0)} />
<input value={y} onChange={() => this.handleChange(1)} />
<input value={z} onChange={() => this.handleChange(2)} />
Upvotes: 1
Reputation: 573
in react you can use state and assign the state var to the value of y and z .
Upvotes: 0