REACT 中父子组件的传参及相互调用方法

父→子传值 和 父→子传方法(子组件调用父组件方法)

1. 子组件调用父组件方法

​ 在父组件中:

import React from 'react'
import ChildCom from './childCom.js'
class ParentCom extends React.Component {
    
handleBtnClick() {
	const action = getAddItemAction();
	store.dispatch(action);
}
    
 render() {
 return (
 <div>
 <h1>父组件</h1>
 <ChildCom 
    content={'我是属于父组件的 要传给子组件的内容'}
    handleBtnClick={this.handleBtnClick.bind(this)} // 父组件方法传给子组件调用
    />
 </div>
 )
 }
}
export default ParentCom;

在子组件中:

import React from 'react'
class ChildCom extends React.Component {
 render() {
 return (
 <div>
 <h2>子组件</h2>
 <div>
 {this.props.content} // 子组件通过 props 接收父组件数据
 {this.props.handleBtnClick()} // 子组件通过 props 调用父组件方法
 </div>
 </div>
 )
 }
}
export default ChildCom;
子→父传值 和 子→父传方法(父组件调用子组件方法)

1. 子组件传递作用域 this 给父组件 父组件可以调用子组件方法

2. ref方法可以接收一个回调函数,表示子组件加载完成后执行的方法,回调函数的参数即为子组件的作用域this,把子组件的作用域 this 赋值给父组件,就可以使用父组件中的方法了

​ 在父组件中:

import React from 'react'
import ChildCom from './ChildCom'
class ParentCom extends React.Component {

   getChildValue(value) {
       console.log(value)// '子组件传给父组件的值'
   } 
   lokka(ref) {
      this.child = ref;
   }  

   render() {
   return (
   <div>
   <h1>父组件</h1>
   <ChildCom 
    onValue={this.getChildValue.bind(this)}
    lokka={this.lokka.bind(this)}// 父组件调用子组件方法 1   
    ref={ref => this.child2 = ref} // 父组件调用子组件方法 2  
      /> 
   </div>
   )
   }
   componentDidMount() {
       
      this.child.replay();// 父组件调用子组件方法 1   
      this.child2.replay();// 父组件调用子组件方法 2   
   }
}
export default ParentCom;

​ 在子组件中:

import React from 'react'
class ChildCom extends React.Component {
    
replay = () => {
	console.log("ok");
}
        
        
 render() {
 return (
 <div>
 <h2>子组件</h2>
 <div>
 {this.props.onValue('子组件传给父组件的值')} // 子组件通过调用父组件传过来的onValue方法把参数传到父组件
 {this.props.lokka(this)} // 将自身作用域的this通过lokka传给父组件 方法1
 </div>
 </div>
 )
 }
}
export default ChildCom;
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值