首页 > 解决方案 > 在 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',}
    ],
};

标签: javascriptreactjs

解决方案


我不完全确定我是否正确掌握了预期的行为。您是否正在尝试实施类似这样的东西?

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>


推荐阅读