尽管状态更改,组件仍不会在react native中重新呈现?

uinbv5nw  于 2022-12-30  发布在  React
关注(0)|答案(2)|浏览(148)

我是一个react原生初学者,尽管状态发生了变化,但仍在努力重新呈现组件,以下是我的组件的省略版本:

export default function HomeScreen({ navigation }) {
  const { getItem } = useAsyncStorage("todo");
  const [selectedItems, setSelectedItems] = useState([]);

  function renderCard({ item }) {
    return (
      <TouchableHighlight
        onLongPress={() => {
          setSelectedItems((selectedItems) => [...selectedItems, item.title]);
        }}
        underlayColor="gray"
      >
        <Card
          style={
            selectedItems.includes(item.title)
              ? styles.cardSelected
              : styles.cardNotSelected
          }
        >
          <Card.Title style={styles.cardTitle}>{item.title}</Card.Title>
        </Card>
      </TouchableHighlight>
    );
  }

  useEffect(() => {
    const unsubscribe = navigation.addListener("focus", getTodoList);

    return unsubscribe;
  }, []);

  return (
    <View>
      <FlatList
        refreshing={loading}
        onRefresh={getTodoList}
        style={styles.list}
        data={items}
        renderItem={renderCard}
        keyExtractor={(item) => item.id}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  cardSelected: {
    backgroundColor: "#444333",
  },
  cardNotSelected: {
    backgroundColor: "#ff2f2f",
  },
});

我基本上想改变背景颜色的卡时,卡是长按,任何帮助是赞赏!

bvjxkvbb

bvjxkvbb1#

<FlatList
  {…otherProps}
  extraData={selectedItems}
/>

使用extraData属性。当提供的值更改时,该属性将导致FlatList重新呈现

w51jfk4q

w51jfk4q2#

我发现问题了。重新渲染没问题,背景色设置错了。
取代:

<Card
      style={
        selectedItems.includes(item.title)
          ? styles.cardSelected
          : styles.cardNotSelected
      }
>

我需要使用containerStyle来更改卡片的背景:

<Card
      containerStyle={
        selectedId === item.id
          ? styles.cardSelected
          : styles.cardNotSelected
      }
>

相关问题