简体   繁体   English

React JS 将数据或子组件传递给父组件

[英]React JS pass the data or child component to parent component

Is it possible to pass the data from the child component to the parent component using props?是否可以使用 props 将数据从子组件传递到父组件?

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

I have a list of item in the child component which came from to the parent component, then I want to send the index of the selected data to the other child component located in the parent component.我在子组件中有一个来自父组件的项目列表,然后我想将所选数据的索引发送到位于父组件中的另一个子组件。

Can't example well, kindly see the attached screenshot for other references.不能很好地举例,请参阅随附的屏幕截图以获取其他参考。 Thanks a lot!非常感谢!

enter image description here在此处输入图像描述

You can keep the data in the Parent component and use a function to pass the props from the child to the Parent.您可以将数据保留在父组件中,并使用 function 将道具从子组件传递给父组件。 This concept is called Lifting State Up where you define the state at the highest common ancestor so all the child components are using the same data which in this case is the selecetd item这个概念被称为提升 State Up在这里您定义 state 在最高的共同祖先,所以所有子组件都使用相同的数据,在这种情况下是选择项

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 component where the selection is made to accept a function properly, something like onSelectionChanged .我认为,最简单的方法是让子组件选择正确地接受 function ,例如onSelectionChanged If you had a button for each item passed to the child you could do something like:如果您为传递给孩子的每个项目都有一个按钮,您可以执行以下操作:

Child Component A子组件 A

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

Child Component B子组件 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 component handles a change in the selection, it invokes the function passed as a prop onSelectionChanged .因此,当您的子组件处理选择的更改时,它会调用作为道具onSelectionChanged传递的 function 。 You can pass whatever data you want from ChildA to that function.您可以将任何您想要的数据从 ChildA 传递到 function。

Note that the parent Component keeps the selected value (from ChildA) in local state, then passes that value to ChildB via a prop.请注意,父组件将选定的值(来自 ChildA)保留在本地 state 中,然后通过道具将该值传递给 ChildB。

You can have a state variable in the parent component and pass it to child components to share data between them.您可以在父组件中拥有一个 state 变量并将其传递给子组件以在它们之间共享数据。 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 component can then use the selectImage prop to select the image然后图像列表组件可以使用 selectImage 属性到 select 图像

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 component to the component.我们有一个父 state 值,并将每个点击子组件更新到该组件。

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>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将数据从子级传递到父级,再传递到另一个子级组件React Js - Pass data from child to parent and to another child component React Js 如何在 React.JS 中将数据从子组件传递到父组件? - How to pass data from child to parent component in React.JS? 在 React.js 中如何将数据从子组件传递到父组件 - How to pass data from a child component to a parent component in React.js 当父组件向子组件传递数据并渲染子组件时显示加载栏。 反应.JS - show loading bar when parent component pass data to and render child component. React.JS 过滤后的数据没有从 React 中的父组件传递到子组件 - filtered data not getting pass from parent component to child component in React 在React中将数据从子组件传递到父组件 - Pass data from child component to parent component in React 通过点击从子组件到父组件反应传递数据 - Pass data via on click from child component to parent component react 无法将 React 表单数据从子组件传递到父组件 - Unable to pass React form data from a Child component to a Parent Component 在React JS中将数据从子组件发送到父组件 - Send data from child component to parent component in react js 在嵌套组件反应js中在子组件和父组件之间传递数据 - passing data between child and parent component in nested component react js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM