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

Jac*_*cob 2 reactjs react-state-management react-hooks

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

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

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>
  )
};
Run Code Online (Sandbox Code Playgroud)

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

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

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

onClick={() => handleClick(item)}
Run Code Online (Sandbox Code Playgroud)

但是你不能用 prop 传递参数。

onClick={(item) => onShowClick}
// Or
onClick={onShowClick(item)}
Run Code Online (Sandbox Code Playgroud)

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

小智 5

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

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>
    )
}
Run Code Online (Sandbox Code Playgroud)

希望这有帮助。