简体   繁体   中英

Get data from one component in another in ReactJs

I have an application in reactjs. I want to get data from the input, from Component.js, into Component2.js. The function that get data from input is stored in sources.js.

 export const getData = e => { const value = e.target.value; console.log(value); return value; };

Unfortunately when i want to get data in Component2, i don't get anything.
Question : How keeping this structure of folders to get data from Component1 in Component2?
Demo https://codesandbox.io/s/vigorous-vaughan-62mqe?file=/src/Component2.js

You can use React Context API to achieve this solution.

you can lifted up your state from child to parent and then pass that data from parent to another child (sibling). Here is the example:

Parent Component

import React, {useEffect, useState} from 'react';
import Child from "./Child";
import Sibling from "./Sibling";

function CParent(props) {

    const [value, setValue] = useState(false);

    function setOpeningValue(value) {
        console.log('From Child to Parent:' + value);
        setValue(value);
    }
    return (
        <div>
            <Child setOpeningValue={setOpeningValue}/>
            <Sibling value={value}/>
        </div>
    );
}
export default CParent;

Child Component

import React, {useEffect, useState} from 'react';

// Child to Parent communication
function Child(props) {
    const {setOpeningValue} = props;
    const [value, setValue] = useState('');

    function clickHandler() {
        setOpeningValue(`changes is ${value}`);
    }

    function changeHandler(event) {
        setValue(event.target.value);
    }

    return (
        <div>
            <input onChange={changeHandler} />
            <button onClick={clickHandler}>pass data to parent</button>
        </div>
    );
}
export default Child;

Sibling Component

import React, {useEffect, useState} from 'react';

function Sibling(props) {
    const {value} = props;

    return (
        <div>
            This value is showing from Child to Parent to Another Child (Sibling): {value}
        </div>
    );
}
export default Sibling;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM