React基础-defaultProps与子元素

2020-01-08  本文已影响0人  码枫云

React中使用static defaultProps作为默认值
在子组件中传入标签后在子组件内部使用 {this.props.children}接收

import React, { Component } from 'react'

class Child extends Component{
    static defaultProps = {   
        title:'没传过来时候显示的标题'
    }
    constructor(props){
        super(props)
        this.state={

        }
    }
    render() {
        return (
            <div>
              {this.props.children} {/* 通过this.props.children取得父组件传过来的全部节点 */}
    <h1>{this.props.title}</h1>
            </div>
        )
    }
}

export default class app6 extends Component {
    constructor(props){
        super(props)
        this.state={
            title:'要传过来的标题'
        }
    }
    render() {
        return (
            <div>
                 <Child title={this.state.title}>
                   <div>
                   <p>有一个p</p>
                   <button>按钮</button>
                   </div>
                </Child>
            </div>
        )
    }
}


上一篇 下一篇

猜你喜欢

热点阅读