欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

react插槽实现

程序员文章站 2022-07-02 23:42:32
...
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class ParentCom extends React.Component {
    constructor(props) {
        super(props)
        console.log(props);
    }
    render() {
        return (
            <div>
                <h1>组件插槽</h1>
                {this.props.children}
                <ChildCom>
                    <h1 data-position="header">这是放在头部的内容</h1>
                    <h1 data-position="main">这是放在主体的内容</h1>
                    <h1 data-position="footer">这是放在尾部的内容</h1>
                </ChildCom>
            </div>
        )
    }
}
class ChildCom extends React.Component {
    render() {
        console.log(this.props);
        let headerCom, mainCom, footerCom
        this.props.children.forEach((item,index) => {
            if (item.props['data-position'] === 'header') {
                headerCom = item
            }else if (item.props['data-position'] === 'main') {
                mainCom = item
            }else {
                footerCom = item
            }
        })
        return (
            <div>
                <div className="header">
                   {headerCom}
                </div>
                <div className="main">
                   {mainCom}
                </div>
                <div className="footer">
                    {footerCom}
                </div>
            </div>
        )
    }
}
ReactDOM.render(
    <ParentCom>
        <h2>子组件1</h2>
        <h2>子组件2</h2>
        <h2>子组件3</h2>
    </ParentCom>,
    document.getElementById('root')
)

父组件ParentCom传入3个h2标签
1.props打印:
react插槽实现
2.通过this.props.children渲染

子组件传3个h1标签
1.this.props打印:
react插槽实现
2.通过this.props.children.forEach()遍历渲染

相关标签: react