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

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>
)}

 

posted @ 2020-03-27 09:20  小伍子  阅读(8896)  评论(0编辑  收藏  举报