class App extends React.Component { constructor() { super(); this.name = "Bob"; this.handleClickTwo = this.handleClickOne.bind(this); } handleClickOne() { alert(this.name); } handleClickThree = () => alert(this.name); render() { return ( <div> <button onClick={ this.handleClickOne }> Click One </button> <button onClick={ this.handleClickTwo }> Click Two </button> <button onClick={ this.handleClickThree }> Click Three </button> </div> ) } } ReactDOM.render(<App />, document.getElementById('app')); <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="app"></div>Estoy tratando de entender más React.js y quería probar algunas cosas. Hacer clic en los botones con la etiqueta "Hacer clic en dos" y "Hacer clic en tres" funciona según lo previsto, lo que significa que muestra una alerta para el nombre "Bob".
Pero cuando hago clic en el botón "Hacer clic en uno", aparece un error que dice que "nombre" es una propiedad indefinida.
¿Estoy malinterpretando React.js o JS en general? ¿El 'esto' en handleClickOne() se refiere a la función en sí y no a lo que hay en el constructor? Y si es así, ¿por qué funciona handeClickTwo?
las funciones no están vinculadas por defecto en javascript. No handleClickOne , por lo que no puede llamar a this.handleClickOne
handleClickTwo está enlazado en su código en el constructor, usando this.handleClickTwo = this.handleClickOne.bind(this) .
handleClickThree usa la sintaxis de campos de clase pública para vincular correctamente la devolución de llamada, por lo que también funciona.
Para enlazar handleClickOne , debe usar this.handleClickOne = this.handleClickOne.bind(this) para enlazarlo en el constructor.
class App extends React.Component { constructor() { super(); this.name = "Bob"; this.handleClickOne = this.handleClickOne.bind(this); this.handleClickTwo = this.handleClickOne.bind(this); } handleClickOne() { alert(this.name); } handleClickThree = () => alert(this.name); render() { return ( <div> <button onClick={ this.handleClickOne }> Click One </button> <button onClick={ this.handleClickTwo }> Click Two </button> <button onClick={ this.handleClickThree }> Click Three </button> </div> ) } } ReactDOM.render(<App />, document.getElementById('app')); <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="app"></div>