zoukankan      html  css  js  c++  java
  • React中中间组件如何传递props属性

    在react中自定义的组件中如果我们想绑上点击click事件时,加上onClick={}并不会起作用。

    因为我们自定义的组件,并不是一个真实的DOM元素,它不存在点击事件,因为它不是最终渲染的页面的元素。

    这时候我们需要在最底层真实的DOM元素上绑定,如下

    <div onClick={this.props.onClick}/>
    

      如果我们只封装一层这样绑定还好,如果是多层而且多个属性,那每一层都要写大量代码,这时候就可以用{...this.props}

    案例 Father——>Middle——>Child

    class Child extends React.Component{
        render(){
            return(
                <ul>
                    <li>{this.props.name}</li>
                    <li>{this.props.age}</li>
                    <li>{this.props.sex}</li>
                </ul>
            )
        }
    }
    class Middle extends React.Component{
        render(){
            return(
                <Child name={this.props.name}
                    age={this.props.age}
                    sex={this.props.sex}/>
            )
        }
    }
    // {...this.props}扩展赋值,一一对应
    class Father extends React.Component{
        render(){
            return(
                <Middle
                {...this.props}
                />
            )
        }
    }
    

      最后调用Father组件时

    <Father name="Jack" age="18" sex="boy"/>

      

  • 相关阅读:
    codeforces 719A:Vitya in the Countryside
    POJ3233 Matrix Power Series
    codevs1409 拦截导弹2
    BZOJ1562 [NOI2009]变换序列
    POJ1325 Machine Schedule
    codeforces 715B:Complete The Graph
    BZOJ1972:[SDOI2010]猪国杀
    浅谈模拟
    BZOJ2548:[CTSC2002]灭鼠行动
    BZOJ1033:[ZJOI2008]杀蚂蚁
  • 原文地址:https://www.cnblogs.com/bobo1/p/12882456.html
Copyright © 2011-2022 走看看