首页 > 解决方案 > 如何将值从子功能组件传递给父类组件?

问题描述

我有一个父类组件和一个子功能组件。我们如何将这种类型的子组件的值传递给父组件 - 我已经看到了一些将值从子类组件传递到父类组件的示例。

父组件

import React from "react";
import ChildComponent from "./ChildComponent/ChildComponent";

class ParentComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [] // An index value is in this state
        };
    }

    render(){
        //can console log the return value from the ChildComponent here if needed 
        return(
            <React.Fragment>
                <ChildComponent indexval = {this.state.data.index} />                                
            </React.Fragment>
        )
    }
}

export default ParentComponent; 

一个 propindexval被传递给子组件,它是一个功能组件,如下所示

子组件

import React from 'react';;
import Button from './Button/Button';

function ChildComponent(props) {
    const newVal=(index) => {
        let retVal = index + 1; //the retValue need to pass to the parent component
    }
    return (
        <React.Fragment>
            <Button onClick={() => newVal(props.index)}>Click</Button>
        </React.Fragment>
    )
}

您可以注意到 ChildComponent 有一个retVal需要传递给父组件的值。我们怎样才能做到这一点

标签: javascriptreactjs

解决方案


父组件

import React from "react";
import ChildComponent from "./ChildComponent/ChildComponent";

class ParentComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [] // An index value is in this state
        };
    }

    handleClick = (value) => {
       // handle changes from child
       console.log(value)
    }
    render(){
        return(
            <React.Fragment>
             // 1. we pass function for child on props
                <ChildComponent handleClick={this.handleClick} indexval = {this.state.data.index} />                                
            </React.Fragment>
        )
    }
}

export default ParentComponent; 

子组件

import React from 'react';;
import Button from './Button/Button';

function ChildComponent(props) {
    const newVal=(index) => {
        let retVal = index + 1;
        // 2. do calculations and send it to parent
        props.handleClick(retVal);
    }
    return (
        <React.Fragment>
            <Button onClick={() => newVal(props.index)}>Click</Button>
        </React.Fragment>
    )
}

推荐阅读