填充的输入不会在REACT中触发onchange事件

时间:2020-05-12 18:57:03

标签: reactjs typescript

如果我用ref设置输入

refName.current.value = 'my value'

然后将在DOM中设置该值,但不会触发onChange事件。

使用裁判时如何触发onchange

import React, { useRef } from 'react';

const AddTodoArea = observer((props: any) => {
  const [name, setName] = useState('')

  const refName = useRef(null);

  return (
    <div>
      <input
        type="text"
        placeholder="Name"
        ref={refName}
        value={name}
        onChange={(e: React.ChangeEvent<HTMLInputElement>): void => {
          console.log('my value is set by a ref')
        }}
      />
  );
});

export default AddTodoArea;

1 个答案:

答案 0 :(得分:1)

请根据您的要求检查此示例。希望对您有帮助。

import React from "react";

export default class NameForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {value: ''};
        this.inputRef = React.createRef();
    }

    onChange = (event) =>{
        this.setState({value: event.target.value});
        alert('onChange is fired');
    };

    clickHandler = (event) =>{
        event.preventDefault();

        // let input = document.querySelector('#message');
        // let nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
        // nativeInputValueSetter.call(input, 'This is value of text input');
        // let customEvent = new Event('input', {bubbles: true});
        // input.dispatchEvent(customEvent);

        // This is based on your requirement
        let nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
        nativeInputValueSetter.call(this.inputRef.current, 'Hi there');
        let customEvent = new Event('input', {bubbles: true});
        this.inputRef.current.dispatchEvent(customEvent);
    };

    render() {
        return (
            <form>
                <label>
                    Name:
                    <input ref={this.inputRef} id="message" type="text" value={this.state.value} onChange={this.onChange}/>
                </label>
                <input type="button" value="Click Me" onClick={this.clickHandler}/>
            </form>
        );
    }
}