【发布时间】: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,没有。