Reac里面封装单标签组件和双标签组件

双标签组件

双标签封装通过this.props.children来获取标签内的元素,主要目的就是能嵌套标签

// 封装好的组件 cm.js
import React, { Component } from 'react';
export default class App extends Component {
    constructor(props){
        super(props);
        this.state = {  
        };
    }
    render() {
        return (
            <div>
                {this.props.text}
                111
                {this.props.children}
            </div>
        )
    }

}

index.js组件调用cm组件

import React, { Component } from 'react';
import CM from './cm'
export default class App extends Component {
    constructor(props){
        super(props);
        this.state = {     
        };
    }
    render() {
        return (
            <CM text='333'>
                <div>222</div>
            </CM>
        )
    }
}

单标签组件

单标签组件跟双标签组件一样,只不过不能嵌套组件,如果要把组件传进去也可以

cm.js组件不变 改变index.js组件传入的props

import React, { Component } from 'react';
import CM from './cm'
export default class App extends Component {
    constructor(props){
        super(props);
        this.state = {
        };
    }
    render() {
        return (
            <CM text={<div>222</div>}/>
        )
    }
}

 

©️2020 CSDN 皮肤主题: 黑客帝国 设计师:上身试试 返回首页