Reputation: 1262
i am learning to pass data between parent and child components via a tutorial. i double checked my code and still couldn't figure out the mistake.
my index.js
import React, {Component} from 'react';
import ReactDom from 'react-dom';
import {Header} from './components/Header';
import {Home} from './components/Home';
class App extends Component {
constructor(){
super();
this.state ={
HomeLink:"home"
};
}
onGreet(){
alert("hello");
}
onChangeLinkName(newName){
this.setState({
HomeLink:newName
});
}
render(){
return (
<div className="container">
<div className="row">
<div className="col-xs-10 col-xs-offset-1">
<Header HomeLink={this.state.HomeLink} />
</div>
</div>
<div className="row">
<div className="col-xs-10 col-xs-offset-1">
<Home
name={"max"}
initialAge={27}
greet={this.onGreet}>
changeLink={this.onChangeLinkName.bind(this)}
<p>This is a paragraph passed from props</p>
</Home>
</div>
</div>
</div>
);
}
}
ReactDom.render(
<App/>, window.document.getElementById("root")
);
Home.js
the button change link onClick event is calling changeLink function which pass the newlink to props.
import React from 'react';
export class Home extends React.Component {
constructor(props){
super();
this.state = {
age:props.initialAge,
status:0,
homeLink:"changed link"
};
setTimeout(() => {
this.setState({
status:1
});
},3000);
}
onMakeOlder(){
this.setState({
age:this.state.age+3
});
}
onChangeLink(){
this.props.changeLink(this.state.homeLink);
}
render(){
return(
<div>
<p>In a new Component</p>
<p>Your name is {this.props.name} and your age is {this.state.age}</p>
<p>{this.state.status}</p>
<hr/>
<button onClick={()=> this.onMakeOlder()}>make me older</button>
<hr/>
<button onClick={this.props.greet}>greet</button>
<hr/>
<button onClick={this.onChangeLink.bind(this)}>change link</button>
</div>
);
}
}
Home.propTypes = {
name:React.PropTypes.string,
age:React.PropTypes.number,
user:React.PropTypes.object,
children: React.PropTypes.element.isRequired,
greet:React.PropTypes.func,
changeLink:React.PropTypes.func
};
the error:-
Uncaught TypeError: this.props.changeLink is not a function
Upvotes: 0
Views: 277
Reputation: 111
There is a typo in the code.
<Home
name={"max"}
initialAge={27}
greet={this.onGreet}>
changeLink={this.onChangeLinkName.bind(this)}
<p>This is a paragraph passed from props</p>
</Home>
Notice how you are closing the Home
component right after setting the property greet
with this character : >
. You want to close it after you set changeLink
as a prop so move that >
down to after this.onChangeLinkName.bind(this)}
That will fix your error and you should be able to move forward.
Upvotes: 1
Reputation: 5428
Switch the prop you're passing to:
changeLink={this.onChangeLinkName}
and in the constructor of the parent:
this.onChangeLinkName = this.onChangeLinkName.bind(this);
Lastly, in your button call:
<button onClick={this.props.changeLink(this.state.homeLink)}>change link</button>
Upvotes: 0