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

React Native开发中如何从onPress事件获取Button组件的title属性值

你当前的写法不生效是因为 React Native 中的onPress触发的事件对象和浏览器 DOM 事件逻辑不同,e.currentTarget不存在对应title属性,Web 端获取 DOM 节点属性的思路不适用于 React Native 组件。

最简单的解决方法是在绑定事件时直接传递需要的 title 参数:

1. 修改JSX绑定逻辑

{...}
<View style={styles.container}> 
  {userForm.map((item) => {
    const btnTitle = item.name.slice(7)
    return (
      <Button 
        title={btnTitle} 
        key={item.info.uuid} 
        onPress={() => handleClick(btnTitle)} 
      />
    )
  })}
</View>
{...}

2. 修改事件处理函数,直接接收参数

const handleClick = (title) => {
  console.log(title);
};

如果担心循环内创建匿名函数带来额外重渲染开销,也可以用柯里化写法优化:

// 事件函数改写为柯里化形式
const handleClick = (title) => () => {
  console.log(title);
};

// JSX绑定不需要额外套箭头函数
<Button 
  title={btnTitle} 
  key={item.info.uuid} 
  onPress={handleClick(btnTitle)} 
/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 05:54:03