react +antd折叠面板新增元素自动展开

最近在使用react+antd开发的时候遇到了折叠面板元素自动展开的难题,普通情况下,Collapse组件的defaultActiveKey关键词就可以完成组件初始化时元素的默认展开了,但在我开发的这个项目中,无法适用于子元素在变动的情况。


我们首先来看一下antd3.26.18的文档中API是怎么写的:
QQ截图20201021151650.png

activeKey参数可以接收一个数组类型,用于确定展开的子面板,这里我们使用一个状态管理参数给他赋值,用于后期的自动渲染。
假设我们使用父组件传递的props参数渲染了整个面板,代码如下:

{/* 图例信息 */}
<Collapse activeKey={this.state.vectorKey} ghost onChange={(key)=>{this.setState({vectorKey:key})}}>
  {this.props.layerManage.vector.map(item => {
    if (item.legend.data && item.show) {
      return (
        <Panel className={style.layerLegend} header={item.name} key={item.id} >
          {/* 图层图例信息 */}
          {item.legend.data.map(item => {
            return (
              <div className={style.legend} key={item.symbol}>
                <div className={style.legendSymbol} style={{background: item.symbol,backgroundSize: '100% 100%'}}></div>
                <div className={style.legendDesc} >{item.value}</div>
              </div>
            )
          })}
        </Panel>
      )
    }
  })}
</Collapse>

那么,在子组件的props更新钩子中可以加上每次传入新的props元素就给state赋值的方法。

// 如果接收到了新的元素,就给默认展开keys加上最新元素的id
componentWillReceiveProps(nextProps) {
  ['vector', 'raster'].map(type => {
    console.log(this.state[type + 'Key'])
    if (nextProps.layerManage[type].length > this.props.layerManage[type].length) {
      let arr = this.state[type + 'Key'];
      arr.push(nextProps.layerManage[type][0].id.toString())
      this.setState({
        [type + 'Key']: arr
      })
    };
  })
}

同时注意onChange API,它可以接收一个切换面板的回调,其中的key是每次面板切换后Collapse组件对应的展开的Key数组,拿到这个key数组以后,我们在每次状态改变时,重新给state赋值,就可以刷新页面了。

posted @ 2020-10-21 16:57  95君  阅读(1799)  评论(0)    收藏  举报