React(7) --react父子组件传参

react父子组件传参react

父级向子级传参:在父组件中,咱们引入子组件,经过给子组件添加属性,来起到传参的做用,子组件能够经过props获取父组件传过来的参数。函数

在父组件中:this

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;

在子组件中:spa

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

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

在子组件中:blog

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;

在父组件中:get

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;
相关文章
相关标签/搜索