初识React(8):父子组件传参

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hope93/article/details/82461292

父级向子级传参

父子组件通信主要用到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;

通过上面例子可以看出,在父组件中,我们引入子组件,通过给子组件添加属性,来起到传参的作用,子组件可以通过props获取父组件传过来的参数

子级向父级传参

在父组件中:

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;

在子组件中:

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)}>向父组件传值123</a>
         </div>
       </div>
     )
   }
}

export default ChildCom;

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

猜你喜欢

转载自blog.csdn.net/hope93/article/details/82461292