React: trigger onChange if input value is changing by state?

后端 未结 9 1914
我在风中等你
我在风中等你 2020-11-30 04:34

Edit: I don\'t want to call handleChange only if the button has been clicked. It has nothing to do with handleClick. I gave an example in the @shubhakhatri

9条回答
  •  Happy的楠姐
    2020-11-30 05:08

    You need to trigger the onChange event manually. On text inputs onChange listens for input events.

    So in you handleClick function you need to trigger event like

    handleClick () {
        this.setState({value: 'another random text'})
        var event = new Event('input', { bubbles: true });
        this.myinput.dispatchEvent(event);
      }
    

    Complete code

    class App extends React.Component {
      constructor(props) {
        super(props)
        this.state = {
        value: 'random text'
        }
      }
      handleChange (e) {
        console.log('handle change called')
      }
      handleClick () {
        this.setState({value: 'another random text'})
        var event = new Event('input', { bubbles: true });
        this.myinput.dispatchEvent(event);
      }
      render () {
        return (
          
    {this.handleChange(e)}} ref={(input)=> this.myinput = input}/>
    ) } } ReactDOM.render(, document.getElementById('app'))

    Codepen

    Edit: As Suggested by @Samuel in the comments, a simpler way would be to call handleChange from handleClick if you don't need to the event object in handleChange like

    handleClick () {
        this.setState({value: 'another random text'})
        this.handleChange();
      }
    

    I hope this is what you need and it helps you.

提交回复
热议问题