Tengo un componente que tiene un campo de entrada y un botón. Quiero agregar un controlador onclick en el botón que usa el valor de la entrada. Puedo hacer esto con querySelector, getElementbyId o tener un elemento de formulario principal, o cambiar la entrada a un componente. Pero lo que quiero saber es si hay una manera directa y fácil de referenciar el elemento.
import React from "react"; export default class UserInput extends React.Component{ constructor(props){ super(props); this.doStuff = this.doStuff.bind(this); } doStuff(){ const inputValue = document.getElementById('new-task').value // I want to replace this // do stuff } render(){ return( <div id="user-input"> <input type="text" id="new-task"></input> <button type="button" onClick={this.doStuff}>Do Stuff!</button> </div> ) } }Creo que puedes hacerlo de esta manera. Solo pruébalo.
import React from "react"; export default class UserInput extends React.Component{ constructor(props){ super(props); this.textInput = React.createRef(); this.doStuff = this.doStuff.bind(this); } doStuff(){ const inputValue = this.textInput } render(){ return( <div id="user-input"> <input type="text" id="new-task" ref={this.textInput}></input> <button type="button" onClick={this.doStuff}>Do Stuff!</button> </div> ) } }