antd Tabs组件动态加载组件内容

ε祈祈猫儿з 提交于 2020-03-27 09:32:14

Tabs的TabPane子组件不支持通过属性传入Component,官方示例的TabPane内容也都只有简单的文本。如果需要在TabPane的内容中动态传入组件,可以利用jsx特性、采用封装高阶组件的方法实现,方法如下:

1、高阶组件定义

class ToTabContent extends React.Component{
    constructor(props){
        super(props)
    }
    render(){
       //通过传入的name属性动态得到自己需要注入的组件,MyComponent首字母要大写
        const MyComponent = pages[this.props.name]
        
        return <MyComponent {...this.props} />
    }
}

 

2、state定义

this.state = {
    panes : [{
        key: 'pageA',
        title: '页面A',
        name: 'pageA'
    },{
        key: 'pageB',
        title: '页面B',
        name: 'pageB'
    }]
}

 

3、根据state定义的内容渲染TabPane,TabPane内容为state中指定名字的组件

{ this.state.panes.map( pane => 
    <TabPane tab={ pane.title } key={ pane.key }>
        <ToTabContent name={pane.name} />
    </TabPane>
)}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!