react 子传参父_react 父子组件之间传值

react父组件调用子组件的方法 父子组件传值​blog.csdn.net

注意点写在上边比较醒目方法必须写成箭头函数,不然this的指向会出问题。

(不用箭头函数的话要用this.fn.bind(this)修正this的指向)

父组件向子组件传值/方法比较简单,都是在属性中传然后在子组件中props获取。

子组件向父组件传值是通过事件进行传值。

父组件向子组件传值

//父组件中

import React, { Component } from "react";

import Child from "./Child";

class Dad extends Component {

constructor(props) {

super(props);

this.state = {

arr:["暴富","暴瘦"],

}

}

render() {

return (

//写在子组件的属性中

)

}

}

export default Dad;

//子组件中

import React, { Component } from "react";

class Child extends Component {

constructor(props){

super(props);

}

render() {

return (

{

//再用props获取

this.props.arr.map(el=>{

return (

{el}

)

})

}

)

}

}

export default Child;

在子组件中调用父组件中的方法

//父组件

import React, { Component } from "react";

import Child from "./Child";

class Dad extends Component {

constructor(props) {

super(props);

}

dadFn=()=>{

console.log("我是父组件中的方法")

}

render() {

return (

)

}

}

export default Dad;

//子组件

import React, { Component } from "react";

class Child extends Component {

constructor(props){

super(props);

}

render() {

return (

在子组件中调用父组件中的方法

)

}

}

export default Child;

子组件向父组件传值

//父组件

import React, { Component } from "react";

import Child from "./Child";

class Dad extends Component {

constructor(props) {

super(props);

this.state = {

txt:"我是尼爸爸"

}

}

fn=(data)=>{

this.setState({

txt:data

})

}

render() {

return (

{this.state.txt}

)

}

}

export default Dad;

//子组件

import React, { Component } from "react";

class Child extends Component {

constructor(props){

super(props);

}

fn=(data)=>{

this.props.cfn(data);

}

render() {

return (

//通过事件进行传值

{this.fn("我是儿子")}}>子组件向父组件传值

)

}

}

export default Child;

父组件调用子组件中的方法

//父组件

import React, { Component } from "react";

import Child from "./Child";

class Dad extends Component {

constructor(props) {

super(props);

this.state = {

arr:["暴富","暴瘦"],

txt:"我是尼爸爸"

}

}

onRef=(ref)=>{

this.Child=ref;

}

click=()=>{

this.Child.childFn();

}

render() {

return (

父组件调用子组件中的方法

)

}

}

export default Dad;

//子组件

import React, { Component } from "react";

class Child extends Component {

constructor(props){

super(props);

}

componentDidMount() {

this.props.onRef(this)

}

childFn=()=>{

console.log("我是子组件中的方法")

}

render() {

return (

)

}

}

export default Child;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值