React实现搜索功能

2,609 阅读1分钟

示例参考《React 学习之道》

输入搜索内容,表格进行显示

初学者小白,如有错误欢迎指正

共三大组件,为了方便全在一个文件里面写,因为简单所以全用函数式组件

----App

----List

---------ListItem

----Search

App组件

const App = () => {
    const [search, setSearch] = React.useState('')
    const stories = [
    {
      title: 'React',
      url: 'https://reactjs.org/',
      author: 'Jordan Walke',
      num_comments: 3,
      points: 4,
      objectID: 0,
    },
    {
      title: 'Redux',
      url: 'https://redux.js.org/',
      author: 'Dan Abramov, Andrew Clark',
      num_comments: 2,
      points: 5,
      objectID: 1,
    },
  ];
    
    const handleChange = event => {
        setSearch(event.target.value)
    }
    
    const filterStories = stories.filter(item => item.title.toLowerCase().includes(search.toLowerCase()))
    
    return (
        <div>
            <h1>My Hacker Stories</h1>
            <Search search={search} onSearch={handleChange} />
            <hr />
            <List list={filterStories} />
        </div>
    )
}

List组件

const List = ({ list }) => {
    return (
        <table>
            <thead>
                <tr>
                  <th>title</th>
                  <th>author</th>
                  <th>num_comments</th>
                  <th>points</th>
                </tr>
            </thead>
            <tbody>
                (
                    list.map(item => <ListItem item={item} />)
                )
            </tbody>
        </table>
    )
}

ListItem组件

const ListItem = ({ item: { title, url, author, num_comments, points, objectID } }) => {
    return (
        <tr key={objectID}>
            <td><a href={url}>title</a></td>
            <td>author</td>
            <td>num_comments</td>
            <td>points</td>
        </tr>
    )
}

Search组件

const Search = ({search, onSearch}) => {
    return(
        <div>
            Search:
            <input value={search} onChange={onSearch} placeholder="仅支持搜索标题(title)" />
        </div>
    )
}

最后效果展示

react搜索功能.png