
在 React Native 项目中使用 Button 组件时出现 “Button is not defined” 错误,根本原因是 React Native 核心库已移除默认导出的 Button,需改用 TouchableOpacity + Text 或显式导入 @react-navigation/elements 中的按钮组件。
在 react native 项目中使用 `button` 组件时出现 “button is not defined” 错误,根本原因是 react native 核心库已移除默认导出的 `button`,需改用 `touchableopacity` + `text` 或显式导入 `@react-navigation/elements` 中的按钮组件。
该错误常见于升级到 React Native 0.72+ 或使用较新 CLI 创建的项目。从 React Native 0.72 起,官方正式弃用了内置的 组件(即 import { Button } from 'react-native'),因其样式僵硬、定制性差且与现代导航生态不兼容。因此,即使你正确配置了 React Navigation 的 navigation 对象,只要仍尝试从 'react-native' 导入 Button,就会触发 ReferenceError: Button is not defined。
✅ 正确做法是:避免使用 Button,改用可完全自定义的触摸响应组件,如 TouchableOpacity、Pressable 或 TouchableHighlight,并配合 Text 实现语义化按钮行为。
以下是推荐的修复方案(以 TouchableOpacity 为例):
// Home.js
import React from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
const Home = ({ navigation }) => {
const handleNavigateToGame = () => {
navigation.navigate('Game');
};
return (
<view style="{{" flex: justifycontent: alignitems: padding:><text style="{{" fontsize: marginbottom:>This is the Home screen.</text><touchableopacity style="{{" backgroundcolor: paddinghorizontal: paddingvertical: borderradius: onpress="{handleNavigateToGame}"><text style="{{" color: fontsize: fontweight:>Go to Game</text></touchableopacity></view>
);
};
export default Home;
⚠️ 注意事项:
不要再写 import { Button } from 'react-native' —— 该导出已不存在,强制使用将导致运行时崩溃;
-
若你依赖 useNavigation 钩子(例如在无 navigation props 的深层组件中),请确保组件位于
内,并显式导入: import { useNavigation } from '@react-navigation/native'; const MyComponent = () => { const navigation = useNavigation(); return ( <touchableopacity onpress="{()"> navigation.navigate('Game')}> <text>Launch Game</text></touchableopacity> ); }; 如需更丰富的按钮样式(如加载态、禁用态、图标支持),建议使用社区成熟方案,如 @react-navigation/elements 提供的 (注意:这是导航库提供的、非 RN 核心组件),或 UI 库如 NativeBase、Tamagui。
? 总结:Button is not defined 不是导航配置问题,而是组件导入错误。React Native 已转向更灵活、可组合的交互原语(Pressable 等)。拥抱这一变化,不仅能解决报错,还能获得更强的可访问性(a11y)、动画控制和主题适配能力。











