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

后端 未结 9 1928
我在风中等你
我在风中等你 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条回答
  •  情书的邮戳
    2020-11-30 05:12

    you must do 4 following step :

    1. create event

      var event = new Event("change",{
          detail: {
              oldValue:yourValueVariable,
              newValue:!yourValueVariable
          },
          bubbles: true,
          cancelable: true
      });
      event.simulated = true;
      let tracker = this.yourComponentDomRef._valueTracker;
      if (tracker) {
          tracker.setValue(!yourValueVariable);
      }
      
    2. bind value to component dom

      this.yourComponentDomRef.value = !yourValueVariable;
      
    3. bind element onchange to react onChange function

       this.yourComponentDomRef.onchange = (e)=>this.props.onChange(e);
      
    4. dispatch event

      this.yourComponentDomRef.dispatchEvent(event);
      

    in above code yourComponentDomRef refer to master dom of your React component for example

    {this.yourComponentDomRef= dom}}>

提交回复
热议问题