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

如何使用React useRef获取点击按钮对应列表项的内容

解决方案

你现在的问题是把ref挂在了整个<ul>上,所以获取的是所有列表项的文本。要拿到点击按钮对应的单个列表项内容,有两种更简单的方式:

方法一:通过事件对象定位父级列表项

直接在点击函数里利用事件对象的target,向上找到最近的<li>元素:

const addButtonHandler = (e) => {
  // 找到当前按钮所在的最近li元素
  const targetLi = e.target.closest('li');
  console.log(targetLi.innerText);
};

// 渲染部分不用改ref,保持原样
<ul>
  <li>
    <button onClick={addButtonHandler}></button>
    Some context here.
  </li>
  <li>
    <button onClick={addButtonHandler}></button>
    More context here.
  </li>
  <li>
    <button onClick={addButtonHandler}></button>
    even more context here.
  </li>
</ul>

closest('li')会从点击的按钮元素开始,向上遍历DOM树找到第一个匹配的<li>,不管按钮有没有嵌套其他元素都能生效。

方法二:直接传递列表项内容(推荐动态列表场景)

如果你的列表是通过数组循环渲染的(比如用map),可以直接把当前项的内容作为参数传给点击函数,不用操作DOM:

// 假设你的列表数据是数组
const listItems = [
  'Some context here.',
  'More context here.',
  'even more context here.'
];

const addButtonHandler = (itemText) => {
  console.log(itemText);
};

// 渲染部分
<ul>
  {listItems.map((text, index) => (
    <li key={index}>
      <button onClick={() => addButtonHandler(text)}></button>
      {text}
    </li>
  ))}
</ul>

这种方式更符合React的数据流思想,不需要依赖DOM操作,代码更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 16:46:37