簡體   English   中英

如何將對象數組中的屬性從子組件發送到父組件?

[英]How to send a property from an array of object from a child component to the parent component?

我有App ,這是父組件,我有Child組件:

Child組件獲取一個稱為items的道具,因此可以根據數據重用它。 它的例子有datadata1data2

問題是我想從父組件設置一個 cookie,設置 cookie 我需要來自data2的屬性link ,但我已經在Child component中映射data2

我可以做些什么來獲取父組件value of the property link以將其作為參數傳遞:

<Child
  onClick={() =>
    handleUpdate('How can I obtain here the string from link of data2?')
  }
  items={data2}
/>

這是整個示例代碼:

import * as React from 'react';
import './style.css';

const data = [
  { title: 'hey', description: 'description' },
  { title: 'hey1', description: 'description' },
  { title: 'hey2', description: 'description' },
];

const data1 = [
  { title: 'hey', description: 'description' },
  { title: 'hey1', description: 'description' },
  { title: 'hey2', description: 'description' },
];

const data2 = [
  { title: 'hey', link: 'link/hey' },
  { title: 'hey1', link: 'link/he1' },
  { title: 'hey2', link: 'link/he2' },
];

export default function App() {
  const [, setCookie] = useCookie('example');

  const handleUpdate = (cookie) => {
    setCookie(null);
    setCookie(cookie);
  };

  return (
    <div>
      <h2>App - Parent</h2>
      <Child items={data} />
      <Child items={data1} />
      <Child
        onClick={() =>
          handleUpdate('How can I obtain here the string from link of data2?')
        }
        items={data2}
      />
    </div>
  );
}

export function Child({ items }) {
  return (
    <div>
      <h2>Child</h2>
      <ul>
        {items.map((item) => {
          return (
            <>
              <p>{item.title}</p>
              <a href={item.link}>Go to title</a>
            </>
          );
        })}
      </ul>
    </div>
  );
}

謝謝!

如果你想從Child組件中獲取鏈接,你可以簡單地在回調中添加一個link參數:

<Child
 onClick={(link) => handleUpdate(link)}
 items={data2}
/>

然后從Child你只需要調用onClick道具:

export function Child({ items, onClick }) { // here make sure to add the prop while destructuring
<a href={item.link} onClick={() => onClick(item.link)}>Go to title</a>

map方法不會改變它被調用的數組,它只是返回一個新數組,這里的items數組根本不會受到影響,所以你可以像這樣正常調用它:

return (
    <div>
      <h2>App - Parent</h2>
      <Child items={data} />
      <Child items={data1} />
      <Child
        onClick={() =>
          handleUpdate(data2[0].link)
        }
        items={data2}
      />
    </div>
  );

此外,您的Child組件需要接受onClick函數作為道具,如下所示:

export function Child({ items, handleClick }) {
  return (
    <div onClick={handleClick}>
      <h2>Child</h2>
      <ul>
        {items.map((item) => {
          return (
            <>
              <p>{item.title}</p>
              <a href={item.link}>Go to title</a>
            </>
          );
        })}
      </ul>
    </div>
  );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM