Is it possible to remove the extra arrow function here?
Nessuno ha ancora preso questa issue.
- Lingua principale
- JavaScript
- Stelle
- 11.8k
- Fork
- 7.9k
- Merge medio
- 1g 11h
- PR unite (30g)
- 11
Descrizione
Hi!
The tutorial has an example like this:
class Square extends React.Component {
render() {
return (
<button
className="square"
onClick={() => this.props.onClick()}
>
{this.props.value}
</button>
);
}
}
This component used in the Board component like this:
renderSquare(i) {
return (
<Square
value={this.state.squares[i]}
onClick={() => this.handleClick(i)}
/>
);
}
We have closed the context in a function that we pass to onClick in the Board component.
But why don't we just pass this.props.onClick to onClick in the Square component? Why are we using closures here if we already have the right context inside?
I wrote like this: (link to codepen)
class Square extends React.Component {
render() {
return (
<button
className="square"
onClick={this.props.onClick}
>
{this.props.value}
</button>
);
}
}
This works successfully
It is clear that the variant from the tutorial will also work. But further it says:
When we modified the Square to be a function component, we also changed onClick={() => this.props.onClick()} to a shorter onClick={props.onClick} (note the lack of parentheses on both sides).
So my variation only works in a functional component? But above it also worked in class components. I think this might confuse some people.
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia leggendo le sezioni collegate del tutorial sul sollevamento dello state e sui componenti funzione, poi confronta i due esempi di onClick e la spiegazione che li accompagna. Verifica se l’esempio del componente di classe deve chiarire la differenza tra passare un callback e invocarlo. Il lavoro è completato quando il tutorial spiega chiaramente perché entrambe le forme funzionano e quando è appropriata la forma più breve.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- javascript, react
- Ambito
- documentation
- Tipo di issue
- Documentazione
- Difficoltà
- 2/5
- Tempo stimato
- 1-3 ore
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 35/100