Is it possible to remove the extra arrow function here?
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- JavaScript
- Sterne
- 11.8k
- Forks
- 7.9k
- Ø Merge
- 1 T. 11 Std.
- Gemergte PRs (30 T.)
- 11
Beschreibung
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.
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne mit dem Lesen der verlinkten Tutorial-Abschnitte zum Hochheben von State und zu Function Components und vergleiche dann die beiden onClick-Beispiele und die dazugehörige Erklärung. Prüfe, ob das Beispiel mit der Klassenkomponente eine Klarstellung dazu benötigt, ob ein Callback übergeben oder aufgerufen wird. Die Aufgabe ist erledigt, wenn das Tutorial klar erklärt, warum beide Formen funktionieren und wann die kürzere Form geeignet ist.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- javascript, react
- Bereich
- documentation
- Issue-Typ
- Dokumentation
- Schwierigkeit
- 2/5
- Geschätzter Aufwand
- 1-3 Stunden
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 35/100