You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何从外部文件访问组件属性?点击按钮打印对应数值

React组件间传递点击值:实现按钮点击打印对应数值

你当前的问题是printNumber函数无法获取到按钮对应的value值,因为点击事件没有携带参数。以下是两种简单的解决方法:

方法一:在父组件中传递参数给点击函数

修改Calculator组件里的handleButtons函数,用箭头函数包裹printNumber并传入对应数值:

import Buttons from "./components/Buttons"

function Calculator() {
  function handleButtons(i) {
    // 通过箭头函数把当前的i作为参数传给printNumber
    return(
      <Buttons value={i} onClick={() => printNumber(i)}/>
    )
  }

  function printNumber(num) {
    console.log(num); // 现在会打印按钮对应的数值
  }

  return (
    <>
      <div>
        {handleButtons(1)}
        {handleButtons(2)}
        {handleButtons(3)}
      </div>
      <div>
        {handleButtons(4)}
        {handleButtons(5)}
        {handleButtons(6)}
      </div>
      <div>
        {handleButtons(7)}
        {handleButtons(8)}
        {handleButtons(9)}
      </div>
    </>
  )
}

export default Calculator 

方法二:在子组件中传递value给点击函数

修改Buttons组件,在原生按钮的点击事件中把props.value作为参数传递给父组件传来的onClick:

function Buttons(props) {
    return (
        // 点击时调用父组件的onClick并传入当前按钮的value
        <button onClick={() => props.onClick(props.value)}>{props.value}</button>
    )
}

export default Buttons

同时修改Calculator里的printNumber函数接收参数:

function printNumber(num) {
  console.log(num);
}

两种方法都能实现点击按钮打印对应数值的效果,你可以根据自己的习惯选择其中一种。

内容的提问来源于stack exchange,提问作者equinox_xy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 21:27:27