jsx,react父传子(Props)

父传递给子组件数据,单向流动,不能子传递给父。(但能操作变相传值给父组件)

props的传值,可以是任意的类型。

 

Props可以设置默认值

HelloMessage.defaultProps = {  name:”老陈”,msg:“helloworld”  }

 

注意:props可以传递函数,props可以传递父元素的函数,就可以去修改父元素的state,从而达到传递数据给父元素。

 

父传子数据传递案例

//在父元素中使用state去控制子元素props的从而达到父元素数据传递给子元素

class ParentCom extends React.Component{
    constructor(props){
        super(props)
        this.state = {
            isActive:true
        }
        this.changeShow = this.changeShow.bind(this)
    }

    render(){
        return (
            <div>
                <button onClick={this.changeShow}>控制子元素显示</button>
                <ChildCom isActive={this.state.isActive} />//this.state.isActive将父组件的数据传入子组件
            </div>
        )
    }

    changeShow(){
        this.setState({
            isActive:!this.state.isActive
        })
    }
}

class ChildCom extends React.Component{
    constructor(props){//props中已有父组件的值
        super(props)
 }
    render(){
        let strClass = null;
        // if(this.props.isActive){//this.props.isActive取父组件的值
        //     strClass = ' active'
        // }else{
        //     strClass = ""
        // }
        strClass = this.props.isActive?" active":"";

        return (
            <div className={"content"+strClass}>
                <h1>我是子元素</h1>
            </div>
        )
    }
}
ReactDOM.render(
    <ParentCom />,
    document.querySelector("#root")
)

 

来自于b站https://space.bilibili.com/40018594?spm_id_from=333.788.b_765f7570696e666f.2

posted @ 2020-12-21 16:58  听声是雨  阅读(778)  评论(0编辑  收藏  举报