javascript - 在 ReactJS 中使用按钮过滤数据
问题描述
我有一个有 4 个属性的状态。最初,所有这些都将设置为 false。但是,当我单击按钮时,特定的按钮将变为 true,并且将显示所有其他值。我正在尝试使用过滤器方法,但我无法这样做。
状态:
state = {
hospitals: [
{ id: 'h1', name: 'Apollo Hospital', city: 'Chennai' },
{ id: 'h2', name: 'Fortis Hospital', city: 'New Delhi'},
{ id: 'h3', name: 'Tata Memorial Hospital', city: 'Mumbai'},
{ id: 'h4', name: 'Lilavati Hospital', city: 'Pune',}
],
};
解决方案
我不完全确定我是否正确掌握了预期的行为。您是否正在尝试实施类似这样的东西?
const { useState } = React,
{ render } = ReactDOM,
rootNode = document.getElementById('root')
const data = {
hospitals: [
{ id: 'h1', name: 'Apollo Hospital', city: 'Chennai' },
{ id: 'h2', name: 'Fortis Hospital', city: 'New Delhi'},
{ id: 'h3', name: 'Tata Memorial Hospital', city: 'Mumbai'},
{ id: 'h4', name: 'Lilavati Hospital', city: 'Pune',}
],
}
const App = () => {
const [filters, setFilters] = useState(
Object.assign(
{},
...data.hospitals.map(({city}) => ({[city]: false}))
)
),
onFilter = ({target:{value}}) =>
setFilters({
...filters,
[value]: !filters[value]
})
return(
<div>
{
Object.keys(filters).map(button => (
<input
type="button"
value={button}
key={button}
onClick={onFilter}
className={filters[button] ? 'activeButton' : ''}
/>
))
}
<ul>
{
data.hospitals.map(({id,name,city}) =>
(!Object.values(filters).some(Boolean) || filters[city]) && (
<li key={id}>{name} ({city})</li>
))
}
</ul>
</div>
)
}
render (
<App />,
rootNode
)
.activeButton {
background-color: orange;
color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><div id="root"></div>
推荐阅读
- javascript - 是否有任何方法可以滚动到确切的关键字,如果它在当前窗口中不可见,我正在使用 wd npm
- javascript - 用于实现淡入的 for 循环中的 setInterval
- matlab - 如何从文本文件 Matlab 创建散点图
- c++ - 在光线追踪器上进行 phong 着色的奇怪颜色
- observable - Promise.resolve 的 rxjs6 中的等价物是什么
- java - Apache FOP fox:使用 PDF 文件时外部文档不起作用
- android - 如何在Android中使线程重复
- graphviz - GraphViz:使用 pos 属性的网格布局问题
- php - php pdo 属性数组
- c# - 对象或列名丢失或为空