简体   繁体   中英

how do i pass data among components using props

friends, I am a React beginner, and I have a problem with passing data between components using props I have three components Users, UserList, and AddUser. In the UserList component, all the users should be displayed and AddUser component contains a form. I want to grab data from the forms and update my state in Users component. My pages are Home, User List and Add New User

import React, { Component } from "react";
import UserList from "./userList";

class Users extends Component {
  state = {
    users: [
      {
        name: "ali",
        lastname: "ahmadi",
        language: "python",
        gender: "male",
        score: 100,
      },
      {
        name: "Ahmad",
        lastname: "moradi",
        language: "JavaScript",
        gender: "male",
        score: 90,
      },
    ],
  };
  removeUser = (name) => {
    let users = this.state.users.filter((user) => {
      return user.name !== name;
    });
    this.setState({
      users,
    });
  };
  render() {
    return (
      <div>
        <UserList users={this.state.users} removeUser={this.removeUser} />
      </div>
    );
  }
}

export default Users;

and my user list components code


import React from "react";
import Users from "./user";

const UserList = (props) => {
  const { users } = props;
  console.log(users);

  return (
    <div className="container">
      <h1 className="text-center mt-4" style={{ fontFamily: "tahoma" }}>
        All Users
      </h1>
    </div>
  );
};

export default UserList;

here is my form component

import React, { Component } from "react";
import Users from "./user";

class AddUser extends Component {
  state = {
    name: "",
    lastname: "",
    language: "",
    score: 0,
    gender: "",
  };
  handleChange = (e) => {
    this.setState({
      [e.target.id]: e.target.value,
      gender: e.target.value,
    });
  };
  handleSubmit = (e) => {
    e.preventDefault();
  };

  render() {
    return (
      <div className="container">
        <form onSubmit={this.handleSubmit} className="col-lg-8 m-auto">
          <fieldset className="form-group">
            <legend>Add New User</legend>

            <div className="form-group ">
              <input
                type="text"
                className="form-control"
                id="name"
                placeholder="Name"
                onChange={this.handleChange}
              />
              <input
                type="text"
                className="form-control my-2"
                id="lastname"
                placeholder="Last Name"
                onChange={this.handleChange}
              />
              <input
                type="text"
                className="form-control my-2"
                id="language"
                placeholder="Language"
                onChange={this.handleChange}
              />
              <input
                type="number"
                className="form-control my-2"
                id="score"
                placeholder="Your Score"
                onChange={this.handleChange}
              />
              <div className="form-check form-check-inline">
                <label className="form-check-label" htmlFor="inlineRadio1">
                  <b style={{ position: "relative", top: -2 }}> Male</b>
                </label>
                <input
                  className="form-check-input mx-2"
                  type="radio"
                  value="male"
                  name="gender"
                  onChange={this.handleChange}
                ></input>
              </div>
              <div className="form-check form-check-inline">
                <label className="form-check-label" htmlFor="inlineRadio1">
                  <b style={{ position: "relative", top: -2 }}> Female</b>
                </label>
                <input
                  className="form-check-input mx-2"
                  type="radio"
                  name="gender"
                  value="female"
                  onChange={this.handleChange}
                ></input>
              </div>
              <br />
              <button className="btn btn-outline-info btn-md mt-2">Add</button>
            </div>
          </fieldset>
        </form>
      </div>
    );
  }
}

export default AddUser;

it prints undefined I don't know what's the problem

You can pass the data through props and get the data from child.

getDataFromUserList() is a props that will recieve the value from the child.

constructor(props){
        super(props);
        this.state = {
            users: [
                {
                    name: "ali",
                    lastname: "ahmadi",
                    language: "python",
                    gender: "male",
                    score: 100,
                },
                {
                    name: "Ahmad",
                    lastname: "moradi",
                    language: "JavaScript",
                    gender: "male",
                    score: 90,
                },
            ],
        };
        this.getDataFromUserList = this.getDataFromUserList.bind(this)
    }
 getDataFromUserList(data){
        // Will get the value in data from the child
        console.log(data);
    }
 <UserList users={this.state.users} removeUser={this.removeUser} getDataFromUserList={this.getDataFromUserList}/>

In the userlist page the function in user getDataFromUserList will get as a props.This props is again passed AddUser component as props name getDataFromAddUser

const UserList = (props) => {
    const { users } = props;

    console.log(users);

    return (
        <div className="container">
            <h1 className="text-center mt-4" style={{ fontFamily: "tahoma" }}>
                All Users
      </h1>
            <AddUser getDataFromAddUser={(data) => { props.getDataFromUserList(data)}} />
        </div>
    );
};

export default UserList;

In the AddUser component the state value set from the form is passed through userlist component using props.From the userlist component the data is passed to the user. You will get the value in addUser at the user component at getDataFromUserList() function

<button className="btn btn-outline-info btn-md mt-2" onClick={() => { this.props.getDataFromAddUser(this.state)}}>Add</button>

You have a typo here, import UserList from "./userList";

It should be import UserList from "./UserList";

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