【问题标题】:How do I pass the ID of the button pressed to the parent component?如何将按下的按钮的 ID 传递给父组件?
【发布时间】:2021-01-26 05:58:08
【问题描述】:

我正在尝试创建一个简单的组件,它显示一组按钮,以便在按下其中一个按钮时,父级知道该按钮的 ID。我已经写了一些代码,但我被困在最后一步,以确定哪个按钮被按下。任何帮助,将不胜感激。谢谢!

function GroupofButtons(props) {
  const groupofBtns = [];
  props.btns.forEach((btn) => {
    groupofBtns.push(<button id={btn} value={btn} key={btn} onClick={() => props.onClick()}>{btn}</button>)
    }
  );
 
  return(
    <>
      {groupofBtns}
    </>
  )
}

function App() {
  // How can the console show the id of the button that was pressed
  const handleClick  = () => console.log("pressed");
  const btn_typs = [1,2,3,];
  return (
    <>Press a button!
      <div>
        <GroupofButtons btns={btn_typs} onClick={() => handleClick()}/>
      </div>
    </>
  )
}

ReactDOM.render(
  <App  />,
  document.getElementById('root')
);

【问题讨论】:

  • 您需要将其作为参数传递给孩子的onClick,例如onClick={() =&gt; props.onClick(btn)},然后在定义该函数的父级中,也定义一个参数:const handleClick = (btn) =&gt; console.log(btn);
  • @Jayce444 - 感谢您的提示 - 我确实尝试过,并且日志显示“未定义” - 我认为问题与我打破孩子的方式有关
  • @jaesle 刚刚看到您如何将其传递下去,是的,这就是问题所在。如果某个东西是一个函数,你可以直接传递它。所以在渲染 GroupofButtons 时,像这样传递 prop:onClick={handleClick}

标签: javascript reactjs react-hooks parent-child


【解决方案1】:

类似这样的:

import React from "react";
import "./styles.css";

const btn_typs = [1, 2, 3];
export default function App() {
  const handleClick = (e) => {
    console.log(e.target.name);
  };

  return (
    <>
      Press a button!
      <div>
        <GroupofButtons btns={btn_typs} handleClick={handleClick} />
      </div>
    </>
  );
}

function GroupofButtons(props) {
  return props.btns.map((btn, i) => (
    <button name={btn} key={i} onClick={props.handleClick}>
      {btn}
    </button>
  ));
}

这是密码笔:https://codesandbox.io/s/suspicious-firefly-czvct?file=/src/App.js

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-16
    • 2013-06-18
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    相关资源
    最近更新 更多