React Error
Fehlermeldung in React :
TypeError: this.props.onClick is not a function
onClick
D:/Programmierung/Web/Demo/React01/React01/ClientApp/src/components/Game_TicTocToe.js:92
89 | return (
90 | <button className="square"
91 | //onClick={()
=> this.handleClick()} //own click()
> 92
| onClick={() => this.props.onClick()} //parent
onClick
| ^ 93 | >
94 | {this.props.value}
95 | </button>
|
Solution:
You have to define an onClick() event in the calling code.
Note: the this.props.onEvent() indicates that when using the components,
the function is defined at the same time.
Simple solution:
Create the Function onClick in Parent Component
Parent Code
The Parent Element Calls a Child Component <Square... > and shown wie
is missing the hidden onClick= . Definition.."
Solution: pass the onClick here when you create it. The word this. points
to an event in the parent itself.
Therefore, the this.onClick function must be defined in the caller. (here
with ) also hidden
class Board extends React.Component {
constructor(props) {
super(props);
this.state = {
squares: Array(9).fill(null),
};
}
renderSquare(i) {
return (
<Square
value={this.state.squares[i]}
//onClick={() => this.handleClick(i)}
/>);
}
// handleClick(i) {
// const squares = this.state.squares.slice();
// squares[i] = 'X';
// this.setState({ squares: squares });
// }
|
Child Component Code
Note: the child tries to run den event from the parent caller.
The event this.props.onClick() meansthat it is defined by the parent caller
when called.
//----------< Child_Component >------------
class Square extends React.Component {
render() {
return (
<button className="square"
//onClick={() => this.handleClick()} //own click()
onClick={() => this.props.onClick()} //parent onClick
>
{this.props.value}
</button>
);
}
}
//----------</ Child_Component >------------
|