【问题标题】:Passing data from one component to the another将数据从一个组件传递到另一个组件
【发布时间】:2021-07-26 18:40:51
【问题描述】:

我是 React 新手,我正在尝试了解如何将数据从一个组件传递到另一个组件。我不知道我做错了什么。在下面的示例中,我认为在表单组件中返回状态就足以在用户列表中使用这些数据,但事实并非如此。有人能解释一下怎么做吗?

function Form({ add }) {
  const [state, setState] = useState({ add });
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [phone, setPhone] = useState(0);

  const addUser = () => {
    setState({
      firstName: firstName,
      lastName: lastName,
      phone: phone,
    });
    return state;
  };

  return (
    <form
      onSubmit={(e) => {
        e.preventDefault();
      }}
    >
      <h1>Team Management</h1>
      <label>First name:</label>
      <br />
      <input
        className="userFirstname"
        name="userFirstname"
        type="text"
        placeholder="First Name"
        onChange={(event) => {
          setFirstName(event.target.value);
        }}
      />
      <br />
      <br />
      <label>Last name:</label>
      <br />
      <input
        className="userLastname"
        name="userLastname"
        type="text"
        placeholder="Last Name"
        onChange={(event) => {
          setLastName(event.target.value);
        }}
      />
      <br />
      <br />
      <label>Phone:</label>
      <br />
      <input
        className="userPhone"
        name="userPhone"
        type="text"
        placeholder="555555555"
        onChange={(event) => {
          setPhone(event.target.value);
        }}
      />
      <br />
      <br />
      <input
        className="submitButton"
        type="submit"
        value="Add member"
        onClick={addUser}
      />
      <hr />
    </form>
  );
}

function Users(props) {
  console.log("props", props); //empty
  return (
    <>
      <table>
        <thead>
          <tr>
            <th>First name</th>
            <th>Last name</th>
            <th>Phone</th>
          </tr>
          <tr>
            <td> {props.firstName} </td>
            <td> {props.lastName} </td>
            <td> {props.phone} </td>
          </tr>
        </thead>
      </table>
    </>
  );
}

function Application(props) {
console.log('props', props); //empty
Users
  return (
    <section>
      <Form />
      <Users value={props} />
    </section>
  );
}

export default Application;

非常感谢!

【问题讨论】:

  • 您找到解决方案了吗?
  • @SulemanAhmad,没有。

标签: reactjs jsx


【解决方案1】:

要在组件之间进行通信,您应该传递在父组件上定义的函数并将其作为参数传递。你用add方法做了什么,在useState上设置它没有意义,你只需要把它当作一个正常的函数来使用。

这是相同的示例,但进行了一些更改以使其正常工作:

function Form({ add }) {
  // const [state, setState] = useState({ add });
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [phone, setPhone] = useState(0);

  const addUser = () => {
    // setState({
    add({
      firstName: firstName,
      lastName: lastName,
      phone: phone
    });
    // return state;
  };

  return (
    <form
      onSubmit={e => {
        e.preventDefault();
      }}
    >
      <h1>Team Management</h1>
      <label>First name:</label>
      <br />
      <input
        className="userFirstname"
        name="userFirstname"
        type="text"
        placeholder="First Name"
        onChange={event => {
          setFirstName(event.target.value);
        }}
      />
      <br />
      <br />
      <label>Last name:</label>
      <br />
      <input
        className="userLastname"
        name="userLastname"
        type="text"
        placeholder="Last Name"
        onChange={event => {
          setLastName(event.target.value);
        }}
      />
      <br />
      <br />
      <label>Phone:</label>
      <br />
      <input
        className="userPhone"
        name="userPhone"
        type="text"
        placeholder="555555555"
        onChange={event => {
          setPhone(event.target.value);
        }}
      />
      <br />
      <br />
      <input
        className="submitButton"
        type="submit"
        value="Add member"
        onClick={addUser}
      />
      <hr />
    </form>
  );
}

function Users({ users }) {
  return (
    <>
      <table>
        <thead>
          <tr>
            <th>First name</th>
            <th>Last name</th>
            <th>Phone</th>
          </tr>
          {users.map(user => (
            <tr>
              <td> {user.firstName} </td>
              <td> {user.lastName} </td>
              <td> {user.phone} </td>
            </tr>
          ))}
        </thead>
      </table>
    </>
  );
}

export default function App() {
  const [users, setUsers] = useState([]);
  const addUser = user => setUsers([...users, user]);
  return (
    <section>
      <Form add={addUser} />
      <Users users={users} />
    </section>
  );
}

你可以在 stackblitz 上看到它:https://stackblitz.com/edit/react-cehone

【讨论】:

    【解决方案2】:

    您将value 作为道具传递,但您没有从value 获取数据,我认为这可能有效。

    function Users(props) {
      console.log("props", props); //nothing here
      return (
        <>
          <table>
            <thead>
              <tr>
                <th>First name</th>
                <th>Last name</th>
                <th>Phone</th>
              </tr>
              <tr>
                <td> {props.value.firstName} </td>
                <td> {props.value.lastName} </td>
                <td> {props.value.phone} </td>
              </tr>
            </thead>
          </table>
        </>
      );
    }
    

    或者你可以只传递价值而不是道具

    function Users({value}) {
      console.log("props", props); //nothing here
      return (
        <>
          <table>
            <thead>
              <tr>
                <th>First name</th>
                <th>Last name</th>
                <th>Phone</th>
              </tr>
              <tr>
                <td> {value.firstName} </td>
                <td> {value.lastName} </td>
                <td> {value.phone} </td>
              </tr>
            </thead>
          </table>
        </>
      );
    }
    
    function Application(props) {
      return (
        <section>
          <Form />
          <Users value={props} />
        </section>
      );
    }
    
    export default Application;
    

    【讨论】:

    • 它没有工作.. =/ 我认为我的表单组件中的 addUser 函数有问题
    【解决方案3】:

    您正在将道具传递给用户组件,但我认为您没有验证这些道具是否具有某些价值。在将道具传递给用户组件之前尝试控制台。

    function Application(props) {
    console.log('props', props); //if you are getting here then pass to Users
    return (
      <section>
       <Form />
       <Users value={props} /> //If not getting props then pass string like 'props' to see that in Users component where you console the props
      </section>
     );
     }
    

    现在在用户组件呈现时检查控制台

    function Users(props) {
    console.log("props", props); //now check here when it renders 
     return (
     //your render data
     );
     }
    

    当你使用 useState Hook 时,为什么还要在 addUser 函数中使用 setState。使用你在 useState 钩子中获得的第二个参数来设置状态。

    【讨论】:

    • 嘿。是的,我验证过了,它是空的。
    • 那么您也应该从将道具传递给应用程序组件的位置发布您的组件。那么我们可以为您提供帮助!
    • 所有组件都在描述中
    猜你喜欢
    • 2018-05-02
    • 2019-12-16
    • 2021-04-16
    • 2019-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多