Reputation: 2954
When trying to pass a function to a child component, that function is undefined. Actually I can not even execute it directly in my class. Would you think there is a typo?
class FriendsPage extends Component {
constructor(props){
super(props);
this.mylog = this.mylog.bind(this);
}
mylog(){
console.log("test debug");
}
renderItem(item) {
return (<User friend={item} key={item.id} mylog={this.mylog}/>);
}
class User extends Component {
constructor(props){
super(props);
}
render() {
this.props.mylog(); // <== This is undefined
...
}
Upvotes: 7
Views: 5585
Reputation: 966
Works fine. Though if you try to render <User />
without prop
named mylog
at any other location, it will be undefined.
class FriendsPage extends React.Component {
constructor(props) {
super(props);
this.mylog = this.mylog.bind(this);
}
mylog() {
console.log("test debug");
}
render() {
return ( < User mylog = {
this.mylog
}
/>);
}
}
class User extends React.Component {
constructor(props) {
super(props);
}
render() {
this.props.mylog();
return <h1 > Hello < /h1>;
}
}
ReactDOM.render( < FriendsPage / > , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Upvotes: 2