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

React Native中点击按钮切换文本显示及代码故障排查

问题分析与修复方案

你的代码核心问题是React Native 的 Button 组件不支持 onClick 属性——这是Web React的事件处理属性,在React Native中,按钮的点击事件需要用 onPress 来绑定。因为用错了事件名,导致按钮点击后完全不会触发状态切换,所以答案始终无法显示。

修正后的代码如下:

import React, { useState } from "react";
import { View, Text, Button } from 'react-native'

const Testing = () =>{
  const [showValue, setShowValue] = useState(false);

  return (
    <View style={{
      backgroundColor: '#f1f1f1',
      justifyContent: 'center', 
      alignItems: 'center',
      flex: 1 // 加上flex:1让内容占满屏幕垂直空间,确保居中效果
    }}>
      <Text>1. What is Lorem Ipsum?</Text>
      <Text>
1. dummy 
2. text
3. Ipsum
4. Lorem
      </Text>
      {showValue ? (
        <Text style={{color: 'green', margin: 10}}>Answer: Lorem</Text>
      ) : null}
      {/* 把onClick替换为onPress */}
      <Button 
        title={showValue ? "Hide Answer" : "Show Answer"} 
        onPress={() => setShowValue(!showValue)} 
      />
    </View>
  );
}

export default Testing;

额外优化点:我把按钮标题改成了动态切换(显示答案时变成“Hide Answer”),同时给外层View加上了flex:1,确保内容在屏幕垂直方向上也能居中,提升体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 19:54:38