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;
  • 相关阅读:
    基于摸板匹配的目標跟蹤算法
    spoj 2713 Can you answer these queries IV
    zoj 3633 Alice's present
    hdu 3642 Get The Treasury
    poj 1195 Mobile phones
    poj 2760 End of Windless Days
    zoj 3540 Adding New Machine
    spoj 1716 Can you answer these queries III
    spoj 1043 Can you answer these queries I
    spoj 2916 Can you answer these queries V
  • 原文地址:https://www.cnblogs.com/juewuzhe/p/10801810.html
Copyright © 2011-2022 走看看