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

React Native中TypeScript无法访问Button onPress的getAttribute问题

React Native + TypeScript:Button onPress中获取自定义属性的正确方式

问题核心原因

  • React Native原生Button组件仅支持官方文档定义的标准Props(如title、onPress、color),自定义属性(如data-code)会被直接忽略,不会传递到事件逻辑中。
  • React Native的GestureResponderEvent事件对象对应原生平台的触摸节点,而非浏览器DOM元素,不存在getAttribute这类Web DOM API方法,这是跨平台事件系统的本质差异。

方案1:直接在回调中传递参数(推荐)

这是最简洁高效的实现方式,无需依赖自定义属性,直接将目标参数绑定到onPress回调:

import React from 'react';
import { Alert, Button, StyleSheet, View } from 'react-native';

const App = () => {
  const _onPressButton = (code: string) => {
    Alert.alert(code);
  };

  return (
    <View style={styles.container}>
      <View style={styles.buttonContainer}>
        <Button
          onPress={() => _onPressButton("note1")}
          title="Light (On)"
        />
      </View>
      <View style={styles.buttonContainer}>
        <Button
          onPress={() => _onPressButton("Note2")}
          title="light (OFF)"
        />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
  },
  buttonContainer: {
    margin: 20,
  },
});

export default App;

方案2:使用TouchableOpacity自定义按钮(灵活扩展)

如果需要自定义按钮样式或更多扩展能力,推荐用TouchableOpacity替代原生Button,它支持自定义Props,且事件逻辑更灵活:

import React from 'react';
import { Alert, TouchableOpacity, Text, StyleSheet, View } from 'react-native';

// 定义自定义按钮的Props类型
interface CustomButtonProps {
  title: string;
  code: string;
  onPress: (code: string) => void;
}

const CustomButton = ({ title, code, onPress }: CustomButtonProps) => {
  return (
    <TouchableOpacity 
      style={styles.customButton}
      onPress={() => onPress(code)}
    >
      <Text style={styles.buttonText}>{title}</Text>
    </TouchableOpacity>
  );
};

const App = () => {
  const _onPressButton = (code: string) => {
    Alert.alert(code);
  };

  return (
    <View style={styles.container}>
      <View style={styles.buttonContainer}>
        <CustomButton 
          title="Light (On)" 
          code="note1" 
          onPress={_onPressButton} 
        />
      </View>
      <View style={styles.buttonContainer}>
        <CustomButton 
          title="light (OFF)" 
          code="Note2" 
          onPress={_onPressButton} 
        />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
  },
  buttonContainer: {
    margin: 20,
  },
  customButton: {
    padding: 10,
    backgroundColor: '#2196F3',
    borderRadius: 4,
  },
  buttonText: {
    color: 'white',
    textAlign: 'center',
  },
});

export default App;

内容的提问来源于stack exchange,提问作者Papp Zoltán

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 22:50:31