![](/img/trans.png)
[英]How to trigger an onChange event on an input when its value changed by code in React?
[英]how to trigger onChange event on text input when the value is changed programmatically - react
render() {
return (
<input
onChange={this.handleChange}
value={this.props.transcript}
type='text
/>
)
}
在上面的示例中,如果使用鍵盤輸入更改了文本值,它將觸發onChange事件,但是如果通過this.props.transcript動態更改了文本值,則不會觸發onChange事件。 如何解決這個問題?
如果我們正確使用react setState,它應該可以正常工作,但是,看起來您有兩組值,一組來自父級“ this.props.transcript”,另一組在輸入框中,由“ this.handleChange”處理。 或者,檢查是否需要反應鈎子,例如“ componentWillUpdate”和“ componentWillReceiveProps”,以將狀態更改應用於輸入。
沒有看到更多代碼,您輸入的抄本值似乎是錯誤的。
請嘗試value = {props.transcript},如果不起作用,請嘗試value = {this.state.transcript}。
您可以使用componentWillReceiveProps掛鈎來實現它,因為您的道具會更新,它將調用componentWillReceiveProps方法。 方法內部是您的游樂場。 請確保每次更改道具時都會調用此方法
import React,{ Component } from 'react'
class InputBox extends Component {
componentWillReceiveProps(nextProps){
// write your logic here or call to the common method
console.log(nextProps.transcript);
}
handleChange(e){
console.log(e.target.value)
}
render(){
return(
<section>
<input
onChange={this.handleChange}
value={this.props.transcript}
type='text'
/>
</section>
);
}
}
export default InputBox;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.