[英]Why changing value in state doesn't trigger onChange of input element in REACT
我輸入了其值由按鈕元素更改的輸入。 我需要一種方法來調用該輸入的onChange
。 當值更改時,我必須進行一些驗證。
我在 StackOverflow 上找到了一些答案,但他們正在使用他們沒有正確解釋或我沒有正確使用它的調度。
但是在更新 state 時不會調用onChange
。 這是我現在所擁有的
<div className="input-group">
<input type="text" className="form-control quantity-field text-center" onChange={(e) => this.handleChange(e)} value={this.state.quantity}/>
<button onClick={(e) => this.handleIncDec(e)}>+</button>
</div>
handleIncDec = (e) => {
e.preventDefault()
this.setState({
quantity: this.state.quantity += 1
})
}
handleChange = e => {
console.log(e.target.value);
const re = /^[0-9\b]+$/;
if (e.target.value === '' || re.test(e.target.value)) {
this.setState({
quantity: e.target.value
})
}
};
輸入的值已正確更新,但永遠不會調用 onChange ,除非我直接在該輸入中更新值而不是使用按鈕,這不是我想要的。
如果您需要任何其他信息告訴我,我會提供。
默認情況下,onChange 事件只會在用戶輸入上調用。 大多數情況下,您可以通過使用生命周期方法(如ComponentDidUpdate
或 React 中的類似方法)以編程方式避免觸發 onChange 事件。 在您的示例中,在我看來,您只需要驗證來自兩個不同來源的輸入,因此我建議使用更簡單的實現。
你可以創建一個驗證函數來代替你可以在handleChange
和handleInDec
上使用嗎?
You should also avoid updating state based on previous state with this.setState({ quantity: this.state.quantity += 1})
, as you are not guaranteed that state always will be updated (Remember, setState
is asynchronous). 而是使用來自setState
的返回值來保證更新的狀態值
class Test extends React.Component { constructor() { super(); this.state = { quantity: 0 }; } handleIncDec = e => { e.preventDefault(); this.setState(prevState => { var newQuantity = prevState.quantity + 1; if (this.isValidInputData(newQuantity)) { return { quantity: newQuantity }; } }); }; handleChange = e => { if (this.isValidInputData(e.target.value)) { this.setState({ quantity: e.target.value }); } }; isValidInputData = newQuantity => { const re = /^[0-9\b]+$/; return newQuantity === "" || re.test(newQuantity); }; render() { return ( <div className="input-group"> <input type="text" className="form-control quantity-field text-center" onChange={this.handleChange} value={this.state.quantity} /> <button onClick={this.handleIncDec}>+</button> </div> ); } } ReactDOM.render(<Test />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.