简体   繁体   中英

Passing in props - Undefined - REACT

I'm not sure where I'm going wrong with this. Essentially, I'm just hoping on passing down my current state as a prop to pass it down the component tree.

Parent is a class component and here is where I start passing the data down:

The state and setting state works. When I console log after submission of the form it shows correct data, but the children cannot seem to access it.

state in parent component:

    class Example extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
              name: "",
              email: "",
              info: ""
            }
          }
        };
      }


    <form>
                <input
                  type="text"
                  name="name"
                  required=""
                  value={this.state.name.value}
                  onChange={this.changeHandler}
                />
                <label>name</label>
              </input>


  changeHandler = event => {
    const name = event.target.name;
    const value = event.target.value;

    this.setState({
      ...this.state.[name]: {
      ...this.state[name], value
    });

in return

  <ExampleComponent2 //An imported component that needs to access the props defined in here
            name={this.state.name}
            email={this.state.email}
            info={this.state.info}
          />

Then in ExampleComponent2 console.log(props.name) returns undefined.

I was also looking to passing the props even further to another component thats inside ExampleComponent2

<Child
    name={props.name}
    email={props.email}
    idinfo{props.info}
  />

but when i try to console log the props in any child component, it returns as undefined.

  • If you are using functional component, you have to define props as a parameter of the functional component

Example:

const Component = (props) => {
          return <ExampleComponent
              name={props.name}
              email={props.email}
              idinfo{props.info}
        />
      }
  • If you are using class component, it's must be this.props.

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