【问题标题】:how to trigger onChange event on text input when the value is changed programmatically - react当以编程方式更改值时如何在文本输入上触发 onChange 事件 - 反应
【发布时间】:2018-12-08 19:28:37
【问题描述】:
render() {
    return (
        <input
            onChange={this.handleChange}
            value={this.props.transcript}
            type='text
        />
    )    
}

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

【问题讨论】:

  • 你为什么需要改变它?这似乎是不必要的要求。
  • 因为我想为键盘输入更改以及 this,props.transcript 更改时触发 onChange 事件@Justcode
  • 这可能会对您有所帮助。 stackoverflow.com/questions/136617/…
  • 查看 componentDidUpdate 方法 (reactjs.org/docs/react-component.html#componentdidupdate) - 它使您可以访问以前的道具,以便您可以比较 props.transcript 值以查看它是否已更改,然后调用 this.handleChange如果需要。

标签: javascript reactjs events


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      没有看到更多的代码,看起来你在输入中的成绩单值是错误的。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-21
        • 2022-11-12
        • 1970-01-01
        • 2018-06-20
        • 1970-01-01
        • 1970-01-01
        • 2017-10-08
        • 1970-01-01
        相关资源
        最近更新 更多