当值以编程方式更改时,如何在文本输入上触发onChange事件-react


render() {
return (
<input
onChange={this.handleChange}
value={this.props.transcript}
type='text
/>
)    
}

在上面的例子中,如果使用键盘输入更改文本值,它将触发onChange事件,但如果通过this.props.transcript动态更改,则不会触发onChange。如何解决这个问题?

您可以使用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;

如果我们正确使用react setState,它应该可以正常工作,但是,看起来你有两组值,一组来自父级"this.props.transcript",另一组在由"this.handleChange"处理的输入框中。或者,检查是否需要像"componentWillUpdate"one_answers"componentWillReceiveProps"这样的react挂钩来对输入应用状态更改。

在没有看到更多代码的情况下,输入中的transcript值似乎是错误的。

尝试value={props.transcription},如果不起作用,则value={this.state.transcription}.

最新更新