Reputation: 33
I can not access to the age when clicking on the button! I get the alert but not the age. Got something like 'His age is [object Object]'.Thank you!
class Hello extends React.Component {
render() {
return ( < div >
<h1>{this.props.name}</h1>
<button onClick={this.props.handleAge}>Click
</button>
< /div >
)
}
}
class App extends React.Component {
alertAge (age) {
alert('His age is ' + age);
}
render() {
return (
<div>
<Hello name="Eric" age={25} handleAge={this.alertAge}/ >
<Hello name="Dyna" age={30} handleAge={this.alertAge}/ >
<Hello name="Boss" age={8} handleAge={this.alertAge}/ >
</div>
);
}
}
Upvotes: 1
Views: 2831
Reputation: 10273
You are not passing a variable to the alertAge
function.
class Hello extends React.Component {
render() {
return (
<div>
<h1>{this.props.name}</h1>
<button onClick={() => { this.props.handleAge(this.props.age) }}>
Click
</button>
</div>
)
}
}
Upvotes: 1
Reputation: 6220
Your function is not being called with the argument you expect, on your Hello component change:
<button onClick={() => {this.props.handleAge(this.props.age)}}>Click</button>
You need to wrap it and pass the variables you need.
Upvotes: 1