<span>{this.state.initialValue * 10}</span>
- самое простое решение.
Прямо сейчас вы умножаете 10 в конструкторе. Этот код выполняется только один раз, поэтому finalValue не обновляется при изменении ввода. Если по какой-либо причине вам нужны две переменные как для начального, так и для конечного значения, вы можете использовать метод componentDidUpdate для обновления окончательного значения при изменении начального значения, как показано ниже:
См. Комментарии в коде для объяснения.
class Test extends React.Component {
constructor(props){ // this code runs only once
super(props);
this.state = { // set both initial value and final value to 0.
initialValue: 0,
finalValue: 0,
};
this.alpha = this.alpha.bind(this);
}
componentDidUpdate(props, state){ // runs everytime after component updates, the arguments props and state are previous props and state before update.
// this check is important, you are doing set state inside componentDidUpdate it must be inside some condition
// otherwise you will be stuck in infinite loop as component updates everytime state changes
if(state.initialValue!==this.state.initialValue){ // if initial value was changed(by function alpha) change final value too.
console.log('input changed'); // just to see it working correctly, remove it later
this.setState({ finalValue: this.state.initialValue * 10 }); // set final value to initial value * 10
}
}
alpha (ev){
this.setState({ [ev.target.name]: ev.target.value });
}
render() {
return (
<div>
<input type="number" value={this.state.initialValue} onChange={this.alpha} name="initialValue" id="initialValue"/>
<span>{this.state.finalValue}</span>
{% or do this and skip componentDidUpdate
<span>{this.state.initialValue * 10}</span> %}
</div>
);
}
}