简体   繁体   中英

'Undefined' passed from parent to child component in React?

I have the following code with a parent and a child class, The parent class is the Container and the child presents the results on the screen.However I am unable to pass values from parent to child. Whenever I try to pass the value, I get undefined

Parent Class

class Container extends React.Component{
    constructor(props) {
        super(props);
        this.state = {course:"Commerce",grade:"10",btnState:"Add"}
}
render(){

        return (
          <Presentation course={this.state.course} grade={this.state.grade} btnState={this.state.btnState}
           />
        );
    }
}

Child Class

class Presentation extends React.Component {
     debug(){
       alert(this.props.course)
     }
    render () {
  return (
    <div>

        <form>

            <input type="text" value={this.props.course} /><br/><br/>
            <input type="text" value={this.props.grade}  /><br/><br/>
            <input type="reset" id="addCourse" value={this.props.btnState} 
  onClick={this.debug.bind(this)}/>
            </form>
    </div>
  );
}
   }

The Rendering

ReactDOM.render(
      <Presentation />
      , 
      document.querySelector("#container1")
    );

The form is rendering correctly but the values are not being passed into the child from the parent. alert(this.props.course} gives undefined

You say you have a container component, but you're directly rendering the child component Presentation .

 ReactDOM.render( <Presentation />, document.querySelector("#container1") );

Try rendering the container, eg

ReactDOM.render(
  <Container />,
  document.querySelector("#container1")
);

And see if that renders the container, creates state, and passes the expected props to Presentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM