react 使用 antd 的 tree组件 defaultExpandAllRows 无法默认展开?

本文探讨了在前端开发中遇到的表格、下拉树及选择树默认展开失效的问题。作者提出解决方案,即通过添加&&运算符确保在数据变更后正确渲染表格,从而实现初始化时的树形结构展开。这个技巧对于优化前端界面交互和提升用户体验具有重要意义。
摘要由CSDN通过智能技术生成
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
可以通过在Tree组件中设置onSelect函数来实现点击节点文字展开收起。 具体实现步骤如下: 1. 在Tree组件中设置onSelect函数,该函数会在节点被选中时触发。 ```javascript <Tree onSelect={onSelect} // 其他属性 > // 树节点 </Tree> ``` 2. 在onSelect函数中判断被选中的节点是否有子节点,如果有则展开节点,否则不做任何操作。 ```javascript const onSelect = (selectedKeys, { node }) => { const { children } = node.props; if (children) { setExpandedKeys(expandedKeys => { const index = expandedKeys.indexOf(selectedKeys[0]); if (index > -1) { // 如果节点已展开,则收起节点 return [...expandedKeys.slice(0, index), ...expandedKeys.slice(index + 1)]; } else { // 如果节点未展开,则展开节点 return [...expandedKeys, selectedKeys[0]]; } }); } } ``` 3. 在Tree组件中设置expandedKeys属性,该属性为展开的节点的key的数组。 ```javascript <Tree onSelect={onSelect} expandedKeys={expandedKeys} // 其他属性 > // 树节点 </Tree> ``` 完整代码如下: ```javascript import React, { useState } from 'react'; import { Tree } from 'antd'; const Demo = () => { const [expandedKeys, setExpandedKeys] = useState([]); const onSelect = (selectedKeys, { node }) => { const { children } = node.props; if (children) { setExpandedKeys(expandedKeys => { const index = expandedKeys.indexOf(selectedKeys[0]); if (index > -1) { // 如果节点已展开,则收起节点 return [...expandedKeys.slice(0, index), ...expandedKeys.slice(index + 1)]; } else { // 如果节点未展开,则展开节点 return [...expandedKeys, selectedKeys[0]]; } }); } } return ( <Tree onSelect={onSelect} expandedKeys={expandedKeys} > // 树节点 </Tree> ); } export default Demo; ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

归来巨星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值