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

React Native按钮onPress无法获取值,更新状态返回undefined

解决React Native Button onPress中无法获取value/title的问题

问题根源

React Native的Button组件和Web端HTML按钮不一样,它的onPress回调不会传入浏览器那种DOM事件对象,所以你用e.target.value或e.target.title自然拿不到值,只会返回undefined。

可行解决方案

方案1:遍历渲染时直接传递目标值

在循环渲染Button的时候,用箭头函数把当前项的PropertyName直接传给点击事件:

{fetchedData.map((fetched)=>{
  return(
    <Button 
      title={fetched.PropertyName} 
      onPress={() => handlePress(fetched.PropertyName)} 
    />
  )
})}

然后修改handlePress函数,直接接收这个值来更新Context:

const handlePress = async (propertyName) =>{
  await setProperty(propertyName);
  alert(`${propertyName} selected`);
  navigation.navigate('Welcome');
}

方案2:补上遍历必需的key属性

另外,React要求遍历渲染组件时必须加唯一的key属性,避免渲染警告,建议补充上:

{fetchedData.map((fetched)=>{
  return(
    <Button 
      key={fetched.PropertyName} // 要是数据里有唯一ID,用ID当key更稳妥
      title={fetched.PropertyName} 
      onPress={() => handlePress(fetched.PropertyName)} 
    />
  )
})}

额外提示:异步更新的坑

setProperty是异步操作,你如果在调用后立刻alert(property),大概率拿到的还是旧值。如果需要在属性更新后执行跳转、弹窗这类操作,可以用useEffect监听property的变化:

useEffect(() => {
  if(property) {
    alert(`${property} selected`);
    navigation.navigate('Welcome');
  }
}, [property, navigation]);

// 这时handlePress可以简化成:
const handlePress = async (propertyName) =>{
  await setProperty(propertyName);
}

内容的提问来源于stack exchange,提问作者VCS-Jacob

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 22:45:29