Home > Back-end >  TypeError: undefined is not an object (evaluating '_this.props.button_click') error from p
TypeError: undefined is not an object (evaluating '_this.props.button_click') error from p

Time:09-04

hello everyone I have a problem with a method. I cannot pass data from the parent class to the child class. My code: Parent class:

import Child from "./Child";

export default class Parent extends Component {
constructor(props){
    super(props); 
        this.state={ author:"Helen"}
} 
Follow(uid){
console.log("ok button pressed")
 }  
render(){
return(<View style={styles.button}>
          <Child text={"Follow"} uid={this.state.author} button_click={this.Follow(this.state.author)}/>
        </View>)
}
}

Now in Child class:

calc=()=>{
  this.props.button_click(this.props.uid);
} 
const Child = ({ text }) => {
  return (
    <TouchableOpacity style={styles.button} onPress={() => this.calc()}>
      <Text style={styles.text}>{text}</Text>
    </TouchableOpacity>
  );
};

now when i hit the button i get the following error: TypeError: undefined is not an object (evaluating '_this.props.button_click') why in the child class does not recognize props.props.button_click? How can I do?

CodePudding user response:

First of all you only declare text as props in your child component, it should be either (props) or ({text, button_click, uid}). Second you can only access the props inside the Component. Assuming Child is a functional component (where you can't use this), replace this

calc=()=>{
  this.props.button_click(this.props.uid);   // Impossible to  access the props here
} 
const Child = ({ text }) => {
  return (
    <TouchableOpacity style={styles.button} onPress={() => this.calc()}>
      <Text style={styles.text}>{text}</Text>
    </TouchableOpacity>
  );
};

By this

const Child = ({ text, button_click, uid }) => {

 const calc = () => {
  button_click(uid);
 } 
 return (
   <TouchableOpacity style={styles.button} onPress={calc}>
     <Text style={styles.text}>{text}</Text>
   </TouchableOpacity>
 );
};

I am not sur that's exactly what you need, if it still does not work, please share your entire Child component.

  • Related