【问题标题】:Get state.filters Array from other outside component using react-table使用 react-table 从其他外部组件获取 state.filters 数组
【发布时间】:2021-09-13 20:13:53
【问题描述】:

您好,我正在尝试使用此示例实现反应表过滤功能。https://react-table.tanstack.com/docs/examples/filtering。但我有一个问题。我创建了一个不同的组件,并在其中调用了我的 react-table 组件。我的意思是我的主要组件是包装表组件。有没有办法在 react-table 组件中获取 state.filters 数组?你能帮我解决这个问题吗?

我的主要组件:

....

import React from 'react'
import DataTable from '../dataTable/Datagrid'; --> imported react-table example different file as component

function List() {

// state management
// I want to call state.filters here to use set for any state

    return (
        <div>
            <DataTable
                            columns={columns}
                            data={ playerState.items}
                            </>
        </div>
    )
}

export default List

...

【问题讨论】:

    标签: reactjs react-hooks react-table-v7


    【解决方案1】:

    根据文档 React Table 是一组用于构建强大的表格和数据网格体验的钩子。这些钩子是轻量级、可组合和超可扩展的,但不会为您呈现任何标记或样式。

    所以你需要使用 useEffect 挂钩来监听状态的变化,然后调用从 List 组件向下传递到表的函数 prop。然后,此函数可以使用 useState Hooks 设置过滤器,如下所示。 // 列表组件

     function List() {
       const [filter, setFilter] = React.useState([])
       function getFilter(filteredValue) {
          setFilter(filteredValue)
       }
       
       return (
          <div>
            <DataTable
                    columns={columns}
                    data={ playerState.items}
                    filter={getFilter}
            </>
          </div>
       )
     }
    

    在你的内部 '../dataTable/Datagrid' 您需要创建监听过滤数据的 useEffect Hook,然后您可以调用函数 getFilter 传递过滤数据作为参数,这将在每次更新过滤数据时更新过滤器状态

    function Datagrid({filter}) {
      // use Effect Here
       useEffect(() => {
         filter(state.filter);
       }, [state]);
    
    }
    

    【讨论】:

    猜你喜欢
    • 2013-08-27
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 2018-10-25
    • 2018-07-11
    • 2019-05-01
    相关资源
    最近更新 更多