最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React JS pass the data or child component to parent component - Stack Overflow

programmeradmin4浏览0评论

Is it possible to pass the data from the child ponent to the parent ponent using props?

-Parent ponent
  --- ItemList ponent.
  --- DisplatSelect ponent from the itemList ponent

I have a list of item in the child ponent which came from to the parent ponent, then I want to send the index of the selected data to the other child ponent located in the parent ponent.

Can't example well, kindly see the attached screenshot for other references. Thanks a lot!

enter image description here

Is it possible to pass the data from the child ponent to the parent ponent using props?

-Parent ponent
  --- ItemList ponent.
  --- DisplatSelect ponent from the itemList ponent

I have a list of item in the child ponent which came from to the parent ponent, then I want to send the index of the selected data to the other child ponent located in the parent ponent.

Can't example well, kindly see the attached screenshot for other references. Thanks a lot!

enter image description here

Share Improve this question asked Jun 2, 2021 at 2:51 Lex Adrian LingadLex Adrian Lingad 251 silver badge5 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

You can keep the data in the Parent ponent and use a function to pass the props from the child to the Parent. This concept is called Lifting State Up where you define the state at the highest mon ancestor so all the child ponents are using the same data which in this case is the selecetd item

function Parent() {
  const [selectedItem, setSelectedItem] = useState(null);
  const data = []; // Your Data
  return (
    <>
      <h1>Your selected Item = {selectedItem}</h1>
      {data.map((item) => {
        <Child item={item} setSelectedItem={setSelectedItem} />;
      })}
    </>
  );
}

function Child({ item, setSelectedItem }) {
  return <Button onClick={() => setSelectedItem(item.id)}> {item} </Button>;
}



The simplest way, I think, is for the child ponent where the selection is made to accept a function properly, something like onSelectionChanged. If you had a button for each item passed to the child you could do something like:

Child Component A

const ChildA = ({ items, onSelectionChanged }) => {
    return (
        <div>
            {items.map((item, index) => (
                <button onClick={() => onSelectionChanged(index)}>Item</button>
            ))}
        </div>
    )
}

Child Component B

const ChildB = ({ selectedItem }) => {
    return (
        <div>
            Selected {selectedItem}
        </div>
    )
}

Parent Component

const Parent = () => {
    const [selection, sets election] = useState({});

    const onSelectionChanged = index => {
        console.log(`ChildA selection changed: ${index}`);
    }

    return (
        <div>
            <ChildA items={items} onSelectionChanged={onSelectionChanged} />
            <ChildB selectedItem={selection} />
        </div>
    )
}

So when your child ponent handles a change in the selection, it invokes the function passed as a prop onSelectionChanged. You can pass whatever data you want from ChildA to that function.

Note that the parent Component keeps the selected value (from ChildA) in local state, then passes that value to ChildB via a prop.

You can have a state variable in the parent ponent and pass it to child ponents to share data between them. I'll post a sample code block on how you can do this for your case.

export default function ParentComponent (props) {
  const data = ['image_1_url', 'image_2_url', ...] // Data for the images
  const [selectedIndex, setSelectedIndex] = useState(-1); // Selected index (-1 represents no selection)
  return (
    <ImageList data={data} selectImage={setSelectedIndex} />
    {(selectedIndex !== -1) ? (<SelectedImage data={data[selectedIndex]} />) : (<No ImageSelected/>)}
  );
}

And the image list ponent can then use the selectImage prop to select the image

export default function ImageList (props) {
  return (
    <div>
      props.data.map((imageUrl, index) => (
        <div onClick={() => {props.setSelected(index)}}>
          <img src={imageUrl}/>
        </div>
      ))
    </div>
  );
}

Yes it's possible. We have one parent state value and update every on click child ponent to the ponent.

import React, { useState } from "react";

const Child1 = (props) => {
  return (
    props.items.map( (item, index) => (
      <button key={index.toString()} onClick={() => { props.updateIndex(item.id) }}>
        {item.name}
      </button>
    ) )
  )
} 

const Child2 = (props) => {
  return (
    <h1>Item selected: {props.selectItem}</h1>
  )
} 

const ParentComponent = () => {
  const listItems = [
    {
      id:1,
      name: "sample name 1"
    },
    {
      id:2,
      name: "sample name 2"
    }
  ]
  const [selectItem, setSelectItem] = useState('None');
  return (
    <>
      <Child1 items={listItems} updateIndex={setSelectItem}/>
      <Child2 selectItem={selectItem}/>
    </>
  )
} 

export default function App() {
  return (
    <div className="App">
      <ParentComponent/>
    </div>
  );
}

发布评论

评论列表(0)

  1. 暂无评论