我对如何使用钩子(或无状态组件)从子组件引发事件感到困惑。也许我在想太多。还是不够!我已经建立了一个简单的例子来说明我的困惑。
假设我们有一个包含一些数据的父组件
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)}
但是你不能用道具传递论据。
onClick={(item) => onShowClick}
// Or
onClick={onShowClick(item)}
也许钩子让我感到困惑。任何方向将不胜感激。
这很容易伙计。检查以下代码。我刚刚对你的代码做了一些修改。
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>
)
}
希望这是有帮助的。
我想你想要结合2。
onClick={(item) => onShowClick(item)}
当您将函数发送给子项时,还需要添加this
,或者在父项之外使它成为常量,onShowClick={this.handleClick}
onClick={() => onShowClick}
是一个错误,没有调用onShowClick
函数。
如果需要使用封闭范围的值,则为:
{ data.data.map(item => (
<li key={item.thing}>{item.info}
<button onClick={() => onShowClick(item)}>Click</button>
</li>
))}
这与hooks
无关。
您应该查看有关如何将参数传递给事件处理程序的文档:https://reactjs.org/docs/handling-events.html#passing-arguments-to-event-handlers
这是文档中的示例。
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
但由于你不需要e
,你只需要通过item
{
data.data.map(item => (
<li key={item.thing}>{item.info}
<button onClick={() => onShowClick(item)}>Click</button>
</li>
))
}