我有2个子组件:一个Categories
选择和一个Search
输入文本和提交按钮。他们都有自己的状态。我必须在父页面中使用这两个组件。我需要知道我必须在哪个类别中进行搜索并实现这一目标,我认为我应该解除这种状态,以便父母可以处理它。
基本上,我从子组件中删除了状态,并将其放置在父组件上,最终得到了这样的代码(简化代码):
export default ParentPage = () => {
const [searchString, setSearchString] = useState("");
const [category, setCategory] = useState(0);
const onSearch = () => {
// search for searchString in the selected category
}
return (
<>
<Categories category={category} setCategory={setCategory} />
<Search searchString={searchString} setSearchString={setSearchString} onSearch={onSearch} />
</>
)
}
这是一个好方法吗?似乎有些冗长,是否有更紧凑的方法将state和setState传递给子组件?
答案 0 :(得分:1)
代替:
<Categories category={category} setCategory={setCategory} />
<Search searchString={searchString} setSearchString={setSearchString} />
您还可以使用下面的一个,因为您保留与州相同的名称道具:
<Categories {...{ category , setCategory }} />
<Search {...{ searchString , setSearchString }} />
注意:但是,从提供的内容中我看不出任何提升状态的目的 代码,所以无话可说。
代码更新后,您可以执行以下操作:
export default ParentPage = () => {
const [searchString, setSearchString] = useState("");
const [category, setCategory] = useState(0);
const onSearch = () => {
// search for searchString in the selected category
// if you are filtering category and calling setCategory, then it's all good
// else you need to pass `searchString` in `Categories` to filter the data
}
return (
<>
<Categories {...{category , setCategory }} />
<Search {...{searchString , setSearchString , onSearch}} />
</>
)
}
答案 1 :(得分:0)
嗨,我在这里准备了一个完整的示例。您需要使用回调将子状态从子状态传递到父状态,然后在父状态上接收子状态,然后将该状态发送给另一个子状态。
父组件
import React, {useEffect, useState} from 'react';
import Child from "./Child";
import Sibling from "../Sibling";
function CParent(props) {
const [status, setStatus] = useState(false);
function setOpeningValue(status) {
console.log('From Child to Parent:' + status);
setStatus(status);
}
return (
<div>
<Child setOpeningValue={setOpeningValue}/>
<Sibling status={status}/>
</div>
);
}
export default CParent;
子组件
import React, {useEffect, useState} from 'react';
// Child to Parent communication
function Child(props) {
const {setOpeningValue} = props;
const [isOpen, setOpen] = useState(false);
function clickHandler() {
setOpen(!isOpen);
setOpeningValue(`changes is ${!isOpen}`);
}
return (
<div>
<button onClick={clickHandler}>Open</button>
</div>
);
}
export default Child;
同级组件
import React, {useEffect, useState} from 'react';
function Sibling(props) {
const {status} = props;
const [isOpen, setOpen] = useState(false);
return (
<div>
From Child to Parent to Another Child (Sibling) {status}
</div>
);
}
export default Sibling;