首页 > 解决方案 > 在 React Native 中更改先前状态的样式属性

问题描述

目前我正在使用 useState 为每次单击的图像添加边框。当我单击图像时,它会正确地给我一个边框,但是当我单击另一个图像时,它会保留以前的图像状态并使其保持活动状态。我想要的是当我按下图像时,单击的前一个图像应该删除它的边框,新图像应该有边框。这是我到目前为止使用的代码,每次点击都会为图像添加一个边框:

const ListItem = (props) => { 

const [background, setBackground] = useState(true);
  const setStyle = (background) => {
    setBackground(background);
  }
  
  const { itemWidth } = props;

  return (
    <TouchableWithoutFeedback>
      <Animated.View
      style={{
          margin: 5,
        }}>
        <View onClick={() => setBackground(current => !current)}
         style={{borderWidth: background? 0:1,
            borderColor: '#000',}}>
        <Image
          style={{
            width: itemWidth,
            height: 50,
          }}
          source={props.image}></Image>
          </View>
      </Animated.View>
    </TouchableWithoutFeedback>
  );
};

这是我从以下位置填充图像的地方:

图片.js:

export default class BottomImages extends Component { 

state = {
    columns: 3,
  };

  render() {
    const { columns } = this.state;
    return (
      <View style={styles.container}>
        <FlatList
          numColumns={columns}
          data={[
            require('../resource/images/AzureDamsel.png'),
            require('../resource/images/BicolourAngelfish.png'),
            require('../resource/images/ClownTriggerfish.png'),
          ]}
          renderItem={({ item }) => {
            return (
              <ListItem
                itemWidth={(ITEM_WIDTH - 10 * columns) / columns}
                image={item}
              />
            );
          }}
          keyExtractor={(index) => {
            return index;
          }}
        />
      </View>
    );
  }
}

如果需要,我还添加了一个沙箱供参考:沙箱代码

标签: reactjsreact-native

解决方案


您可以通过管理活动图像 ID 来实现这一点。

这里的基本思想是为每个图像添加一个唯一的 Id。并保留一个 Active Id 以跟踪当前点击了哪张图片。

state = {
    columns: 3,
    activeItemIndex: -1
  };

平面列表应该看起来像 -

<FlatList
          numColumns={columns}
          data={[{
            id: 1,
            image: require('../resource/images/AzureDamsel.png')
          },
          {
            id: 2,
            image: require('../resource/images/BicolourAngelfish.png')
          },
          {
            id: 3,
            image: require('../resource/images/ClownTriggerfish.png')
          }]}
          renderItem={({ item }) => {
            return (
              <ListItem
                itemWidth={(ITEM_WIDTH - 10 * columns) / columns}
                image={item.image}
                itemIndex={item.id}
                activeItemIndex={activeItemIndex}
                onChangeActiveItemIndex={(index)=>{
                  this.setState({
                    activeItemIndex: index
                  })
                }}
              />
            );
          }}
          keyExtractor={(index) => {
            return index;
          }}
        />

我修改了代码,这里更新了Link。代码并没有完全按照它应该的方式工作。但我希望你明白这一点。


推荐阅读