Editar: no quiero llamar a handleChange solo si se ha hecho clic en el botón. No tiene nada que ver con handleClick. Di un ejemplo en el comentario de la respuesta de @shubhakhatri.
Quiero cambiar el valor de entrada según el estado, el valor está cambiando pero no activa el método handleChange() . ¿Cómo puedo activar el método handleChange() ?
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'}) } render () { return ( <div> <input value={this.state.value} onChange={this.handleChange}/> <button onClick={this.handleClick.bind(this)}>Change Input</button> </div> ) } } ReactDOM.render(<App />, document.getElementById('app'))Aquí está el enlace de codepen: http://codepen.io/madhurgarg71/pen/qrbLjp
Debe activar el evento onChange manualmente. En las entradas de texto, onChange escucha los eventos de input .
Entonces, en su función handleClick , necesita activar un evento como
handleClick () { this.setState({value: 'another random text'}) var event = new Event('input', { bubbles: true }); this.myinput.dispatchEvent(event); }Código completo
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 ( <div> <input readOnly value={this.state.value} onChange={(e) => {this.handleChange(e)}} ref={(input)=> this.myinput = input}/> <button onClick={this.handleClick.bind(this)}>Change Input</button> </div> ) } } ReactDOM.render(<App />, document.getElementById('app')) Editar: como sugirió @Samuel en los comentarios, una forma más sencilla sería llamar a handleChange desde handleClick si don't need to the event object en handleChange como
handleClick () { this.setState({value: 'another random text'}) this.handleChange(); }Espero que esto sea lo que necesitas y te ayude.
Probé las otras soluciones y nada funcionó. Esto se debe a que se ha cambiado la lógica de entrada en React.js. Para más detalles, puede ver este enlace: https://hustle.bizongo.in/simulate-react-on-change-on-controlled-components-baa336920e04 .
En resumen, cuando cambiamos el valor de la entrada cambiando el estado y luego despachamos un evento de cambio, React registrará tanto el setState como el evento y lo considerará un evento duplicado y lo tragará.
La solución es llamar al setter de valor nativo en la entrada (consulte la función setNativeValue en el siguiente código)
Código de ejemplo
import React, { Component } from 'react' export class CustomInput extends Component { inputElement = null; // THIS FUNCTION CALLS NATIVE VALUE SETTER setNativeValue(element, value) { const valueSetter = Object.getOwnPropertyDescriptor(element, 'value').set; const prototype = Object.getPrototypeOf(element); const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set; if (valueSetter && valueSetter !== prototypeValueSetter) { prototypeValueSetter.call(element, value); } else { valueSetter.call(element, value); } } constructor(props) { super(props); this.state = { inputValue: this.props.value, }; } addToInput = (valueToAdd) => { this.setNativeValue(this.inputElement, +this.state.inputValue + +valueToAdd); this.inputElement.dispatchEvent(new Event('input', { bubbles: true })); }; handleChange = e => { console.log(e); this.setState({ inputValue: e.target.value }); this.props.onChange(e); }; render() { return ( <div> <button type="button" onClick={() => this.addToInput(-1)}>-</button> <input readOnly ref={input => { this.inputElement = input }} name={this.props.name} value={this.state.inputValue} onChange={this.handleChange}></input> <button type="button" onClick={() => this.addToInput(+1)}>+</button> </div> ) } } export default CustomInputResultado
Creo que deberías cambiar eso así:
<input value={this.state.value} onChange={(e) => {this.handleChange(e)}}/> Eso es, en principio, lo mismo que onClick={this.handleClick.bind(this)} como lo hizo en el botón.
Entonces, si desea llamar a handleChange() cuando se hace clic en el botón, entonces:
<button onClick={this.handleChange.bind(this)}>Change Input</button>o
handleClick () { this.setState({value: 'another random text'}); this.handleChange(); }