下面是我试图更改被点击按钮的 colored颜色 的代码.计划是有更多的按钮(一周中的每一天一个).单击时-更改所单击按钮的 colored颜色 ,并将所有其他按钮 colored颜色 重置为默认 colored颜色 .现在,我正在硬编码InitialArr[0].color=‘red’,但计划将其放入一个if循环中.当我单击该按钮时,将调用changeColorB2,但第一个按钮的 colored颜色 没有变化.蒂娅.

const initialArr = [
  {
    id: 1,
    color: "#e3e3e3",
    text: "Mon, 11",
  },
  {
    id: 2,
    color: "#e3e3e3",
    text: "Tue, 12",
  },
];

const changeColorB2 = (buttonInfo) => (e) => {
  console.log("Callllllleedddd ", buttonInfo);
  initialArr[0].color = "red";
};

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

<View style={{ flex: 1, marginRight: -1 }}>{buttonsListArr}</View>;

推荐答案

您应该使用useState来更新 colored颜色 :

const initialArr = [
  {
    id: 1,
    color: "#e3e3e3",
    text: "Mon, 11",
  },
  {
    id: 2,
    color: "#e3e3e3",
    text: "Tue, 12",
  },
];
const [data, setData] = useState(initialArr)

const changeColorB2 = (buttonInfo, index) => {
  console.log("Callllllleedddd ", buttonInfo);
  let newArr = [...data];
  newArr[index].color = "red";
  setData(newArr);
};

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

<View style={{ flex: 1, marginRight: -1 }}>{buttonsListArr}</View>;

React-native相关问答推荐

单击时更改ToucheableOpacity colored颜色 不起作用

在 React Native 中,水平滚动不适用于我的整个应用程序

Error: Invariant Violation: Touchable child must either be native or forward setNativeProps to a native component stack

我如何限制 FlatList 中的元素并增加负载?

React Native Android:how to remove "overscroll effect" of ScrollView

如何在 React Native 中测量我的应用程序的数据使用情况?

React Native 获取视图相对于屏幕的绝对位置

如何实时从 react-native-camera 获取帧

由于依赖关系,在 run-android 上构建失败

如何将参数传递给graphql片段?

Property body[41] of BlockStatement expected node to be of a type ["Statement"] but instead got "AssignmentExpression"

路由状态没有通过 redux 保持在 react-native

try 添加包时出现错误duplicate entry:com/google/android/gms/internal/zzble.class

错误:无法解析模块`buffer`

React Native + React (for web) 种子元素

React Native 从导航堆栈中清除上一个屏幕

React Native - __DEV__ 未定义

在不使用 3rd 方库的情况下,在react-native中显示主屏幕之前显示启动画面

Mapping children of a parent component

安卓启动问题:Unsupported class file major version 57