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

Lifting State with hooks (from a mapped array)

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

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

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

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

我想你想结合 2.

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

还需要在将函数发送给child时加上this或者在Parent之外做成常量,onShowClick={this.handleClick}

onClick={() => onShowClick} 是一个错误,onShowClick 函数没有被调用。

如果需要使用封闭范围内的值,则为:

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

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

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

希望这对您有所帮助。

这与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>
  ))
}