我是新来的反应者,我正在尝试建立一个网站,使用户可以在搜索栏中编写查询并返回一些结果。
我创建了两个组件:Searchform
(父级)和Searchbar
(子级)。
我知道如何更新孩子的状态:
function Searchbar() {
const [query, setQuery] = useState("");
return(
<TextField
defaultValue=""
placeholder="Search"
label="Search bar"
fullWidth
onChange={(event)=>setQuery(event.target.value)}
/>
)
}
但是,我不确定如何将此新状态发送给父级。
function Searchform() {
function handleSubmit() {
console.log(query)
}
const [query, setQuery] = useState("");
return(
<form onSubmit={handleSubmit}>
<div className="searchbar">
<Searchbar /> # I think I have to do something here but not sure what.
</div>
<Button variant="contained" color="primary" type="submit">
Submit your search
</Button>
</form>
)
}
答案 0 :(得分:1)
您需要在父级中维护查询,并将值和onChange传递给子级:
function Searchbar({ value, onChange }) {
return (
<TextField
placeholder="Search"
label="Search bar"
fullWidth
value={value}
onChange={onChange}
/>
);
}
function Searchform() {
function handleSubmit() {
console.log(query);
}
const [query, setQuery] = useState('');
//create onChange function that will never
// change during component life cycle
const onChange = useCallback(
e => setQuery(e.target.value),
[]
);
return (
<form onSubmit={handleSubmit}>
<div className="searchbar">
{/* pass value and onChange */}
<Searchbar value={query} onChange={onChange} />
but not sure what.
</div>
<Button
variant="contained"
color="primary"
type="submit"
>
Submit your search
</Button>
</form>
);
}
答案 1 :(得分:0)
应将状态提升到处理该状态的最顶层容器,然后通过props(或上下文提供者)向下传递。
要更新状态,必须将回调函数(通过props)从父级传递到子级组件,以允许子级更新父级状态。然后,更改将在重新渲染期间传播到所有子项。
这是通用的React概念,无论使用钩子还是类see the React documentation
一个基本示例:
const Parent = () => {
const [query, setQuery] = useState(null);
return <Child onQuery={setQuery} />;
}
const Child = ({ onQuery }) => (
<TextField onChange={event => onQuery(event.target.value)} />
);
答案 2 :(得分:0)
希望这会有所帮助,
function Searchform() {
function handleSubmit() {
console.log(query)
}
const [query, setQuery] = useState("");
return(
<form onSubmit={handleSubmit}>
<div className="searchbar">
<Searchbar setQuery={setQuery} />
</div>
<Button variant="contained" color="primary" type="submit">
Submit your search
</Button>
</form>
)
}
function Searchbar({setQuery}) {
// const [query, setQuery] = useState("");
return(
<TextField
defaultValue=""
placeholder="Search"
label="Search bar"
fullWidth
onChange={(event)=>setQuery(event.target.value)}
/>
)
}