react中如何實現類似VUE的具名效果

在子組件中使用this.props時,該屬性有一個children屬性,使用該屬性即可獲取父組件包含的內容
例如:

import React from 'react'

class JobManagement extends React.Component{
    constructor(props){
        super(props)
        this.state = {
            isShow: false
        }
    }

    toggleLayer = () => {
        this.setState({
            isShow: !this.state.isShow
        })
    }

    onCancel = () => {
        this.setState({
            isShow: false
        })
    }

    render(){
        return (
            <React.Fragment>
                <Layer
                    isShow={this.state.isShow}
                    onCancel={this.onCancel}
                >
                    123
                    <div>1</div>
                    <p>sdfasf</p>
                </Layer>
            </React.Fragment>
        )
    }
}

export default JobManagement
import React from 'react'
import 'layer.styl'

class Layer extends React.Component{
    constructor(props){
        super(props)
    }

    render(){
        return (
            <div style={{display: this.props.isShow ? 'block' : 'none'}}>
                <div className={'mask'} onClick={this.props.onCancel}/>
                <div className={'layerWrap'}>
                    <div className={'layer'}>
                        <div className={'layerHead'}>
                            <div className={'layerHeadTitle'}>添加</div>
                        </div>
                        <div className={'layerBody'}>
                           

                            {
                                this.props.children
                            }
                            
                        </div>
                        <div className={'layerFooter'}>
                            <Button onClick={this.props.onCancel} className={'cancelButton'}>取消</Button>
                            <Button className={'confirmButton'}>提交</Button>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}

export default Layer

如上,使用this.props.children即可實現類似具名效果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章