zoukankan      html  css  js  c++  java
  • React(7) --react父子组件传参

    react父子组件传参

    父级向子级传参:在父组件中,我们引入子组件,通过给子组件添加属性,来起到传参的作用,子组件可以通过props获取父组件传过来的参数。

    在父组件中:

    import React from 'react'
    import ChildCom from './childCom.js'
    class ParentCom extends React.Component {
     render() {
       return (
         <div>
            <h1>父组件</h1>
            <ChildCom content={'我是父级过来的内容'}/>
         </div>
       )
     }
    }
    export default ParentCom;

    在子组件中:

    import React from 'react'
    class ChildCom extends React.Component {
       render() {
         return (
           <div>
             <h2>子组件</h2>
             <div>
               {this.props.content}
             </div>
           </div>
        )
    } } export
    default ChildCom;

    子级向父级传参:在父组件中给子组件添加一个属性,这个属性的内容为一个函数,然后在子组件中调用这个函数,即可达到传递参数的效果

    在子组件中:

    import React from 'react'
    class ChildCom extends React.Component {
       valueToParent(value) {
         this.props.onValue(value);
       }
       render() {
          return (
             <div>
                <h2>子组件</h2>
               <div>
                 <a onClick={this.valueToParent.bind(this,123)}>向父组件传值567</a>
               </div>
            </div>
       )
      }
    }
    export default ChildCom;

    在父组件中:

    import React from 'react'
    import ChildCom from './childCom.js'
    class ParentCom extends React.Component {
       state = {
         getChildValue: ''
       }
       getChildValue(value) {
         this.setState({
            getChildValue: value
         })
       }
       render() {
          return (
            <div>
               <h1>父组件</h1>
               <div>子组件过来的值为:{this.state.getChildValue}</div>
               <ChildCom onValue={this.getChildValue.bind(this)}/>
           </div>
         )
      }
    }
    export default ParentCom;
  • 相关阅读:
    【SpringBoot1.x】SpringBoot1.x 安全
    WebStorm快捷键(Mac版)
    iOS 容联离线消息推送
    iOS使用TestFlight进行内部和外部人员测试
    iOS Runtime常用方法整理
    模仿斗鱼直播
    一个很好用的侧滑框架ICSDrawerController实现的 QQ 侧滑及换肤功能
    swift3.0 项目引导页
    使用 swift3.0高仿新浪微博
    swift 监听键盘弹出的高度
  • 原文地址:https://www.cnblogs.com/juewuzhe/p/10801810.html
Copyright © 2011-2022 走看看