简体   繁体   English

React Native:按下TouchableOpacity时更改视图颜色

[英]React Native : change View color when TouchableOpacity is pressed

I have 2 TouchableOpacity each having a View inside it.我有 2 个 TouchableOpacity,每个里面都有一个 View。

I need to change View's backgroundColor to blue when its TouchableOpacity is pressed and to return to the initial backgroundColor when its TouchableOpacity is pressed a second time.我需要在按下其 TouchableOpacity 时将 View 的 backgroundColor 更改为蓝色,并在第二次按下其 TouchableOpacity 时返回到初始 backgroundColor。

Here I don't want to use state because I have 2 or more TouchableOpacity so I need to have a state for every component .在这里我不想使用 state,因为我有 2 个或更多 TouchableOpacity,所以我需要为每个组件设置一个 state

Here is my code :这是我的代码

<TouchableOpacity>
<View style={{backgroundColor:'green'}}>
</View>
</TouchableOpacity>

<TouchableOpacity>
<View style={{backgroundColor:'yellow'}}>
</View>
</TouchableOpacity>

You can do this by using a single state and change backgroundColor by checking its value for ex:您可以通过使用单个状态来完成此操作,并通过检查其值来更改背景颜色,例如:

Initial a data it contain id and initial color:初始化一个包含 id 和初始颜色的数据:

const DATA = [
  {
    id: 1,
    isSelected: false,
    initialBg: 'green',
  },
  {
    id: 2,
    isSelected: false,
    initialBg: 'red',
  },
  {
    id: 3,
    isSelected: false,
    initialBg: 'yellow',
  },
  {
    id: 4,
    isSelected: false,
    initialBg: 'black',
  },
];

Here I initialise the isSelected to false and initial color to a id, Now we need to change isSelected to true and change its color to blue when user taps on that button.在这里,我将 isSelected 初始化为 false,将初始颜色初始化为 id,现在我们需要将 isSelected 更改为 true,并在用户点击该按钮时将其颜色更改为蓝色。

const [isSelected, setIsSelected] = useState(DATA);
const onItemSelect = (item) => {
    let newState;
    if (item.isSelected) {
      newState = isSelected.map((isSelectedItem) =>
        isSelectedItem.id === item.id
          ? {...isSelectedItem, isSelected: false}
          : {...isSelectedItem},
      );
    } else {
      newState = isSelected.map((isSelectedItem) =>
        isSelectedItem.id === item.id
          ? {...isSelectedItem, isSelected: true}
          : {...isSelectedItem},
      );
    }
    setIsSelected(newState);
  };

return(
<View>
  {isSelected.map((item) => (
          <TouchableOpacity onPress={() => onItemSelect(item)} key={item.id}>
            <View
              style={{
                backgroundColor: item.isSelected ? 'blue' : item.initialBg,
                width: 50,
                height: 50,
              }}></View>
          </TouchableOpacity>
        ))}
</View>
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM