所以我有一个函数,当单击菜单项时,它会在div中显示数据。
const [activeCollapseKey, setActiveCollapseKey] = React.useState(0);
const [ drawerContent, setDrawerContent ] = useState(<div></div>);
let info = [];
function handleClick(index) {
const divTitle = "Residence info";
let res = openData.info;
const {data} = res;
info = [];
_.isArray(data) ? residencesInfo = data : residencesInfo.push(data);
let collapse = <Collapse accordion activeKey={[activeCollapseKey]} onChange={(key) => {
// @ts-ignore
setActiveCollapseKey(key);
}}>
{info.map((data, idx) => {
return <Panel header='test' key={idx + 1}>
testInfo
</Panel>
})}
</Collapse>;
setDrawerContent(<div className="open-data-information-drawer-item residences">
<h1>{divTitle}</h1>
<div className="open-data-item-information-container">
{collapse}
</div>
</div>);
}
这个函数将一些jsx加载到下面的div中。(我使用Ant Design组件折叠和列表(
<List
className={ 'list-body' }
dataSource={ Object.keys(predefinedMenuItems) }
renderItem={ predefinedMenuItemId => (
<List.Item >
<div key={predefinedMenuItemId} onClick={ () => handleClick(predefinedMenuItemId)} className={'list-item'}>
<i className={ menuItemIconStyle(predefinedMenuItemId) }></i>
<span>{ predefinedMenuItems[predefinedMenuItemId].tooltip + ' info' }</span>
</div>
</List.Item>
)}
/>
<div className="data-item-information">
{drawerContent}
</div>
现在我的问题是,当我单击菜单项(例如,项目1,请参见屏幕截图1(时,折叠显示得很好。然而,如果我单击折叠中的另一个项目,则不会有任何作用,但当我再次单击菜单中的同一项目时,它会重新加载折叠,并显示折叠中单击的项目(请参见屏幕截图2(。
如何使"折叠"在单击时工作,而不是在再次单击菜单项后工作?
第一次点击项目1的布局截图/点击下拉列表中的项目后的布局截图(折叠(,然后再次点击项目1
避免将渲染组件存储在状态中;React的行为将不可预测,因为这不是一个受支持的用法。相反,将最少量的数据存储在状态中,并根据状态进行渲染:
const [activeCollapseKey, setActiveCollapseKey] = React.useState(0);
const [showDrawerContent, setShowDrawerContent] = useState(false);
let info = [];
function handleClick(index) {
setShowDrawerContent(true);
}
function renderDrawerContent() {
if (!showDrawerContent) return <div></div>;
const divTitle = "Residence info";
let res = openData.info;
const { data } = res;
info = [];
_.isArray(data) ? (residencesInfo = data) : residencesInfo.push(data);
return (
<div className="open-data-information-drawer-item residences">
<h1>{divTitle}</h1>
<div className="open-data-item-information-container">
<Collapse
accordion
activeKey={[activeCollapseKey]}
onChange={key => {
// @ts-ignore
setActiveCollapseKey(key);
}}
>
{info.map((data, idx) => {
return (
<Panel header="test" key={idx + 1}>
testInfo
</Panel>
);
})}
</Collapse>
</div>
</div>
);
}
然后使用它:
<div className="data-item-information">{renderDrawerContent()}</div>