简体   繁体   中英

Is it possible to trigger onChange event with setState?

Does react onChange event only triggers when user types into a input field?

I want to set a dirty flag on a form so when user navigates out of a page it will trigger a dialog asking if he really want to discard changes. The isDirty flag is in my component's state and it is set when user types into input fields. I was afraid that when i initialize state in constructor with predefined input values it might accidentialy trigger onChange resulting in state change and leading to setting isDirty to true when user didn't even type into a field.

Right now it works. Is this expected behavior and am I 100% safe?

Code example: are there any chances handleChange will be triggered by initializing state in constructor or setting state in button onClick handler?

class ExampleComponent extends React.Component {
    constructor(props) {
      super(props);
      this.state = { exampleInput: "exampleValue" };
    }

    handleChange = (event) => {
      this.setState({
         exampleInput: event.target.value,
      });
    }

    onExampleButtonClick = () => {
      this.setState({
         exampleInput: "buttonClicked",
      })
    }

    render() {
      return (
        <div>
          <input name="exampleInput" value={this.state.exampleInput} onChange={this.handleChange}/>
          <button onClick={this.onExampleButtonClick}>Example Button</button>
        </div>
      );
    }
}

Yes you can use componentDidUpdate and check state inside there if the condition is valid you could do something like this

var ev2 = new Event('input', { bubbles: true});
input.dispatchEvent(ev2);

where input would be a ref to the element you want to trigger the event upon more on refts here: https://reactjs.org/docs/refs-and-the-dom.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM