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

React Native中点击TouchableOpacity无法改变颜色问题求助

解决按钮点击后颜色不更新的问题

问题原因

你直接修改了initialArr里的属性,但这个数组不是React的状态变量,React无法感知到它的变化,所以组件不会重新渲染,按钮颜色自然没变化。

修复方案

用React的useState来管理按钮状态,状态更新时会自动触发组件重渲染,颜色就能正常变化了。

修改后的完整代码

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

const ButtonColorDemo = () => {
  // 用useState初始化按钮状态
  const [buttons, setButtons] = useState([
    {
      id: 1,
      color: "#e3e3e3",
      text: "Mon, 11",
    },
    {
      id: 2,
      color: "#e3e3e3",
      text: "Tue, 12",
    },
  ]);

  const changeColorB2 = (buttonInfo) => () => {
    // 创建新数组,更新选中按钮的颜色,其他重置为默认值
    const updatedButtons = buttons.map(btn => {
      return btn.id === buttonInfo.id 
        ? { ...btn, color: 'red' } 
        : { ...btn, color: '#e3e3e3' };
    });
    setButtons(updatedButtons);
  };

  const buttonsListArr = buttons.map((buttonInfo) => (
    <TouchableOpacity
      style={{ backgroundColor: buttonInfo.color, flex: 1, padding: 15, margin: 5 }}
      onPress={changeColorB2(buttonInfo)}
      key={buttonInfo.id}
    >
      <Text>{buttonInfo.text}</Text>
    </TouchableOpacity>
  ));

  return (
    <View style={{ flex: 1, flexDirection: 'row', marginRight: -1 }}>
      {buttonsListArr}
    </View>
  );
};

export default ButtonColorDemo;

关键说明

  • 用useState保存按钮数组,确保状态更新能触发组件重渲染
  • 更新状态时必须创建新的数组对象(不能直接修改原数组),React通过引用变化来检测状态更新
  • changeColorB2函数里用map生成新数组,给当前点击的按钮设为红色,其他按钮恢复默认灰色

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 08:18:18