Esto es lo que hago cuando quiero que this de mis funciones de clase se vincule a la instancia de clase (componente). ¿Hay alguna forma más fácil/más adecuada de hacer esto en React?
class App extends Component { state = { currentSection: 1, message :{text:''} }; constructor(props) { super(props); this.prevSection = this.prevSection.bind(this); this.nextSection = this.nextSection.bind(this); this.mobileChanged = this.mobileChanged.bind(this); } }Podría usar arrow function en lugar del método de clase
Con la función de flecha , no habrá this context , por lo que no tendrá que vincularlo
class App extends Component { state = { currentSection: 1, message: { text: '' }, }; prevSection = () => {} nextSection = () => {} mobileChanged = () => {} }Ejemplo en vivo:
Si no recuerdo mal, si cambias:
function nextSection() {...}a
const nextSection = () => {...} Después de este cambio, puede eliminar this y el bind .
Por favor, hágame saber si su componente seguirá siendo tan funcional como antes. No estoy seguro de si esto cambiará el comportamiento.