Skip to content
Advertisement

Props in component are undefined

i have parent component

export default class Cities extends Component {
  constructor(props) {
    super(props);
    this.state = {
      answer: "",
      input: "",
    };
    this.answerChange = this.answerChange.bind(this);
    this.inputChange = this.inputChange.bind(this);
  }

  answerChange = (e) => {
    this.setState({
      answer: e,
    });
  };
  inputChange = (e) => {
    this.setState({
      input: e,
    });
  };
  
  render() {
    console.log(this.state.answer);
    console.log("this.state");

    return (
      <View style={{ backgroundColor: "#F3F3F6" }}>
        <Text style={styles.title}>Города</Text>
        <ScoreArea props={this.state} />
        <CitiesArea props={this.state} inputChange={this.inputChange} answerChange={this.answerChange} />
      </View>
    );
  }
}

and child component

export default class CitiesArea extends Component{
  constructor(props) {
    super(props);
    this.state = {
    };
  }

  backend = (text, answer)=>{
    /*request*/
    });
  }
  render() {
    console.log(this.props)
    console.log(this.props.answer)
    console.log(this.props.input)
    return (
      <View style={styles.form}>
        <Text style={styles.form__text}>Ответ:</Text>
        <View style={styles.input}>
          <Text style={styles.answer}>
            {this.props.answer}
          </Text>
        </View>
        <Text style={styles.form__text}>Ваш вариант:</Text>
        <TextInput
          style={styles.input}
          placeholder='Пишите здесь'
          onChangeText={text=>{this.props.inputChange(text)}}
        />
        <View style={styles.button}>
          <Icon.Button style={styles.icon} backgroundColor={"#2e167d"} name="arrow-right" size={39} color={"#F3F3F6"}
                       onPress={()=> {
                         this.backend(this.props.input, this.props.answerChange)
                       }}>
          </Icon.Button>
        </View>
      </View>
    );
  }
};

In the console i get the output:

{“answerChange”: [Function bound ], “inputChange”: [Function bound ], “props”: {“answer”: “”, “input”: “”}}

undefined

undefined

The functions that I pass work and the props changes, but when accessing the props value, i get undefined. Moreover, if you refer to the value in the parent, then everything works

Advertisement

Answer

If you want all the PARENT states to CHILD as props. you need to use spread operator like {…this.state}

<ScoreArea {...this.state} />
<CitiesArea {...this.state} inputChange={this.inputChange} answerChange={this.answerChange} />
Advertisement