gpt4 book ai didi

reactjs - 用钩子(Hook)提升状态(来自映射数组)

转载 作者:行者123 更新时间:2023-12-02 00:20:13 26 4
gpt4 key购买 nike

我对应该如何使用 Hook (或更确切地说是无状态组件)从子组件引发事件感到困惑。也许我想太多了。或者还不够!我构建了一个简单示例来说明我的困惑。

假设我们有一个包含一些数据的父组件

import React, { useState } from "react";
import ReactDOM from "react-dom";

const Parent = () => {
const data = [
{
thing: 1,
info: "this is thing 1"
},
{
thing: 2,
info: "this is thing 1"
},
{
thing: 3,
info: "this is thing 3"
}
];

function handleClick(item) {
console.log(item);
}

return (
<div>
<h1> This is the Parent </h1>
<Child data={data} onShowClick={handleClick} />
</div>
)
};

以及通过数据映射创建的子组件

const Child = (data, {onShowClick}) => {
return (
<ul>
{ data.data.map(item => {return (
<li key={item.thing}>{item.info}
<button onClick={() => onShowClick}>Click</button>
</li>
)})}
</ul>
)
}

如果这一切都在同一个组件中找到,我会做类似的事情

onClick={() => handleClick(item)}

但是你不能通过 prop 传递参数。

onClick={(item) => onShowClick}
// Or
onClick={onShowClick(item)}

也许钩子(Hook)让我感到困惑。任何方向将不胜感激。

最佳答案

这很容易,伙计。检查下面的代码。我刚刚对您的代码进行了一些更改。

const Parent = () => {
const data = [
{
thing: 1,
info: "this is thing 1"
},
{
thing: 2,
info: "this is thing 2"
},
{
thing: 3,
info: "this is thing 3"
}
];

const handleClick = (item) => {
console.log(item);
}

return (
<div>
<h1> This is the Parent </h1>
<Child data={data} onShowClick={handleClick} />
</div>
)
};

const Child = (props) => {
return (
<ul>
{props.data.map(item => {
return (
<li key={item.thing}>{item.info}
<button onClick={() => props.onShowClick(item)}>Click</button>
</li>
)
})}
</ul>
)
}

希望对您有所帮助。

关于reactjs - 用钩子(Hook)提升状态(来自映射数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55719293/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com