javascript - 在 React 中如何更新功能组件的状态?
问题描述
我遇到了一个问题,我创建了一个功能组件来呈现下拉菜单,但是我无法更新主 App.JS 中的初始状态。我不确定如何更新状态,除非它在同一个组件中。
这是我的 App.js 的一个片段,我在其中初始化了 items 数组并调用了功能组件。
const items = [
{
id: 1,
value:'item1'
},
{
id: 2,
value:'item2'
},
{
id: 3,
value:'item3'
}
]
class App extends Component{
state = {
item: ''
}
...
render(){
return{
<ItemList title = "Select Item items= {items} />
这是我的功能组件。本质上是我观看的 YouTube 教程的下拉菜单 ( https://www.youtube.com/watch?v=t8JK5bVoVBw )。
function ItemList ({title, items, multiSelect}) {
const [open, setOpen] = useState (false);
const [selection, setSelection] = useState([]);
const toggle =() =>setOpen(!open);
ItemList.handleClickOutside = ()=> setOpen(false);
function handleOnClick(item) {
if (!selection.some(current => current.id == item.id)){
if (!multiSelect){
setSelection([item])
}
else if (multiSelect) {
setSelection([...selection, item])
}
}
else{
let selectionAfterRemoval = selection;
selectionAfterRemoval = selectionAfterRemoval.filter(
current =>current.id == item.id
)
setSelection([...selectionAfterRemoval])
}
}
function itemSelected(item){
if (selection.find(current =>current.id == item.id)){
return true;
}
return false;
}
return (
<div className="dd-wraper">
<div tabIndex={0}
className="dd-header"
role="button"
onKeyPress={() => toggle(!open)}
onClick={() =>toggle(!open)}
onChange={(e) => this.setState({robot: e.target.value})}
>
<div className="dd-header_title">
<p className = "dd-header_title--bold">{title}</p>
</div>
<div className="dd-header_action">
<p>{open ? 'Close' : 'Open'}</p>
</div>
</div>
{open && (
<ul className ="dd-list">
{item.map(item =>(
<li className="dd-list-item" key={item.id}>
<button type ="button"
onClick={() => handleOnClick(item)}>
<span>{item.value}</span>
<span>{itemSelected(item) && 'Selected'}</span>
</button>
</li>
))}
</ul>
)}
</div>
)
}
const clickOutsideConfig ={
handleClickOutside: () => RobotList.handleClickOutside
}
我尝试在功能组件中传递道具并改变状态,但没有任何改变。我怀疑它需要在 itemSelected 函数中进行更改,但我不确定如何。任何帮助将不胜感激!
解决方案
在函数组件中,您拥有状态变量的设置器。在您的示例中,您可以直接使用setOpen(...)
or setSelection(...)
。如果是布尔状态变量,您可以使用setOpen(!open)
. 有关详细信息,请参阅https://reactjs.org/docs/hooks-state.html(“更新状态”一章)。
推荐阅读
- c# - 在asp mvc上按下拉列表排序
- ios - 简单 SpriteKit 场景中的资产大小问题
- c# - getJSON 在第二次请求时丢失路径中的控制器
- python - ValueError:无法将大小为 1048576 的数组重塑为形状 (1024,1024,3)
- lbph-algorithm - 边界上的局部二进制模式像素?
- java - 如果进程终止,Redisson Cache Map 不会驱逐
- mysql - 自定义数据库结果 [Symfony 4]
- php - Symfony - 工作流组件 - 无法识别的选项“元数据”
- detection - 检测 AWS Elastic 部署失败
- typescript - MSBuild TypeScript 不重新生成所有 JS 文件