Soy nuevo en reaccionar, y no puedo entender por qué el botón simple no funciona.
export default class PlayerList extends Component { constructor(props) { super(props) this.state = { players: [], convocPlayers: [] } this.sendConvoc = this.sendConvoc.bind(this) } async sendConvoc() { try { let data = this.state.convocPlayers; await axios.post('/players/convoc', { players: data }); } catch (error) { alert(error) } } render() { return ( <div> <PlayerForm addPlayer={(user) => this.addPlayer(user)}></PlayerForm> </div> <div className="flex items-center justify-between mt-8"> <span className="text-3xl">Liste des joueurs</span> <PrimaryButton onClick={() => this.sendConvoc}>Envoyer la convocation</PrimaryButton> </div> ) } }Mi componente PrimaryButton:
export default class PrimaryButton extends React.Component { render () { return ( <button type={this.props.type} onClick={() => this.onClick} className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"> {this.props.children} </button> ) } onClick() { var clickFunction = this.props.onClick || null; if (clickFunction) { clickFunction() } } }La función sendConvoc nunca se activa cuando hago clic en el "PrimaryButton", si alguien tiene una solución, gracias de antemano
Debe cambiar la función onClick a onClick={() => this.onClick()} o simplemente onClick={this.onClick}
Debemos entender por qué su función no se activa. Cuando especificamos un evento, es decir, onClick , React espera que pasemos una función, no llamemos a la función.
✅ Correcto - Pasando una función
<PrimaryButton onClick={this.sendConvoc}> // passing an inline function <PrimaryButton onClick={() => this.sendConvoc()}> <PrimaryButton onClick={() => alert('hello')}>Para la función en línea, tenga en cuenta que necesitamos llamar a la función interna; de lo contrario, la función en línea devolverá la definición de la función (sin llamar a la función).
❌ Incorrecto - llamando a una función
<PrimaryButton onClick={this.sendConvoc()}> <PrimaryButton onClick={alert('hello')}> Para su caso, la solución en el componente PrimaryButton es llamar a la función dentro de la función en línea. Además, probablemente no necesitemos una función en línea allí, que es una solución más simple.
// BEFORE // the issue here is we forgot to call `this.onClick`, we return function definition of `this.onClick` here. <button type={this.props.type} onClick={() => this.onClick} // AFTER <button type={this.props.type} onClick={() => this.onClick()} // or <button type={this.props.type} onClick={this.onClick} // simpler En el componente PlayerList
// BEFORE <PrimaryButton onClick={() => this.sendConvoc}> // AFTER <PrimaryButton onClick={() => this.sendConvoc()}> // or <PrimaryButton onClick={this.sendConvoc}>