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
...
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With