【问题标题】:get access to selected row data from outside table component从外部表组件访问选定的行数据
【发布时间】:2023-03-17 12:28:01
【问题描述】:

我有一个用于表格的通用组件,该组件通过应用程序在不同页面中使用。现在,行的选择被保存在表格组件本身中。我想在按下按钮时从其父组件访问选定的数据行

这是一个例子 https://codesandbox.io/s/naughty-pond-3e5jp

【问题讨论】:

  • “每当按下按钮”,你指的是什么按钮?
  • @rzwnahmd 我在表格组件外有一个按钮,我的示例中有它

标签: reactjs react-table


【解决方案1】:
@jiltender 

    i fix my problem by doing this to get row data outside the table 
    
        rowProps={row =>(console.log(row)
                )} 
        

add this on parent components where u call the Table 
     <Table
            sortByProps={[]}
            columns={columns}
            rowProps={row =>(setSelectedItems(row))}  /// pass row props
           
          />
    
and the table side 
add this in 
function props 
` `rowProps = () => ({}) }) 

    function Table({ columns, data, showSpinnerProp, hiddenColumnsProps,getCellProps, getRowProps, height, sortByProps, source, 

    setSelectedItems,rowProps = () => ({}) }) {
        
        this will return u all the select data  you can call it before return 
        useEffect(() => {
            setSelectedItems = selectedFlatRows;
            rowProps(selectedFlatRows)
          }, [selectedFlatRows]);
        
        }

【讨论】:

  • 您能否改进答案的格式?有点不清楚
【解决方案2】:

您可以做的是在父组件中为 selectedRows 维护一些状态,然后将回调传递给 Table 组件,每次选择或取消选择一行时都会调用该组件。这里我对你的沙箱做了一些改动,希望对你有帮助:)

https://codesandbox.io/s/naughty-sun-3nhue?file=/src/App.js

【讨论】:

  • 这种方法的问题是我们在两个地方维护选定的行数据。一个是 react-table 本身,另一个是我们的组件
  • 不,我们没有在父组件中维护任何东西,我们只是在访问数据。当 Table 组件发生变化时,我们不会删除或添加父状态中的行,所有这些都由 Table 组件完成。我们只是获取数据,仅此而已
  • 如果您查看您的示例,您会发现 selectedRows 处于您存储所有选定状态的状态。
  • 是的,它只是存储在那里,当我们必须在选择/取消选择一行时同时更改 Table 组件状态和父组件状态时,它会成为一个问题。但我们并没有这样做,我们只是在 Table 组件中进行更改,这些更改会自动反映在 selectedRows 中。
  • 是的,但所选行数据再次重复两​​次,一次在反应表中,一次在我们的父组件状态中
【解决方案3】:

在组件外部创建一个状态变量,类似于

const [selectedRows, setSelectedRows] = useState([]);

然后通过 props 将其传递给组件。然后在按钮上你可以有一些这样的代码

onPress = { () => props.setSelectedRows(selectedRows) }

【讨论】:

  • 动作按钮位于表格组件之外
猜你喜欢
  • 2014-09-05
  • 1970-01-01
  • 2020-02-27
  • 1970-01-01
  • 2017-12-26
  • 2023-04-04
  • 2015-10-13
  • 2019-12-13
  • 1970-01-01
相关资源
最近更新 更多