代码
Parent.js
import Child from "./Child";
export default function Parent() {
function child(name, setName) {
return (
<>
<input
placeholder="Please Input"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</>
);
}
return (
<>
<Child child={child()} />
</>
);
}
Child.js
import { useState } from "react";
export default function Child({ child }) {
const [name, setName] = useState("");
const [list, setList] = useState([]);
function onSubmit(e) {
e.preventDefault();
if (name === "") {
console.log("Please enter a name");
} else {
setList([...list, name]);
setName("");
console.log("Name added to List");
}
}
return (
<>
<form onSubmit={onSubmit}>
{child(name, setName)}
<button type="submit">Submit</button>
</form>
</>
);
}
嗨,我一直在尝试从子函数获取数据,然后通过父函数传递数据。
因此,在child中,我希望它通过child函数,以便Parent可以获得名称setName,然后将其发送回child,以便将其添加到列表中。如果你还有任何问题,请在下面的评论部分留下,我会尽力回答。谢谢
Codesandbox链接:https://codesandbox.io/embed/heuristic-lamarr-u6fzbd?fontsize=14&隐藏导航=1&主题=深色
在将方法作为道具发送时不要调用该方法(在您的情况下是子方法)
import Child from "./Child";
export default function Parent() {
function child(name, setName) {
return (
<>
<input
placeholder="Please Input"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</>
);
}
return (
<>
<Child child={child} /> {/* pass the child method it like this */}
</>
);
}