gpt4 book ai didi

javascript - 单击按钮一次显示一个列表

转载 作者:行者123 更新时间:2023-12-02 23:00:19 25 4
gpt4 key购买 nike

enter image description here我有一个网页,我使用 React JS 表显示记录列表,每一行都有一个按钮,向用户显示操作项列表。如果用户单击一行中的一个按钮,然后单击另一行中的另一个按钮,以前的列表应该隐藏,但两个列表都显示。如何解决这个问题?

const dataset = [
{"id" : 1, "buttons" : (<ActionItemList />)},
{"id" : 2, "buttons" : (<ActionItemList />)}
]

<ReactTable data={dataset} />

const ActionItemList = () => {
return (
<div>
<button>...</button>
</div>
<div>
<ul>
<li>action-item1</li>
<li>action-item2</li>
<li>action-item3</li>
</ul>
/>
</div>
</div>
)
}

最佳答案

如果您可以使用钩子(Hook),您可以让菜单使用包装器传递的方法设置 openId。以下是如何执行此操作的示例:

import React, { useState, memo, useMemo } from 'react';
import ReactTable from 'react-table';
//make ActionItemList a pure component using React.memo
const ActionItemList = memo(
({ isOpen, setOpenId, id }) =>
console.log('in render', id) || (
<button
onClick={() =>
isOpen ? setOpenId() : setOpenId(id)
}
>
{isOpen ? 'Close' : 'Open'} Menu
</button>
)
);
const dataset = [
{ id: 1 },
{ id: 2 },
{ id: 3 },
{ id: 4 },
];
const columns = [
{ id: 1, accessor: 'id' },
{
id: 2,
//if accessor is a function table will render what function returns
// passing in the data where we added isOpen and setOpenId
accessor: ({ Menu, ...props }) => (
//passing in the needed props to pure component Menu
<Menu {...props} />
),
},
];
//wrap this on your react table, adding isOpen and setOpenId
export default () => {
//set state for open id
const [openId, setOpenId] = useState();
//memoize creating the data prop based on openId changing
const dataWithProps = useMemo(
() =>
dataset.map(item => ({
...item,
isOpen: item.id === openId,
setOpenId,
Menu: ActionItemList,
})),
[openId]
);
//return the react table with the extra props in data
return (
<ReactTable data={dataWithProps} columns={columns} />
);
};

关于javascript - 单击按钮一次显示一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57818603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com