javascript - View 在 onPress 后不重新渲染

标签 javascript react-native

我正在尝试在触发 onPress 事件时更改 React Native Card 组件的背景颜色。虽然我在 componentDidUpdate 上看到了状态的变化,但我没有将其可视化。

我在触发 onPress 事件时更改 itemsPressed 数组的值。如果按下的项目 ID 已经在数组中,则将其删除,否则将其添加到数组中。

export default class Popular extends Component {

 constructor(props) {
    super(props);
    this.togglePressed = this.togglePressed.bind(this);

    this.state = {
     categories: [],
     itemsPressed: []
   }
 }

 togglePressed = item => {
    const id = item.id;
    this.setState(({ itemsPressed }) => ({
      itemsPressed: this.isItemPressed(item)                       
      ? itemsPressed.filter(a => a != id)                            
      : [...itemsPressed, id],
    }))
 };

 isItemPressed = item => {
  const id = item.id;
  return this.state.itemsPressed.includes(id);
 };

 componentDidMount() {
   this.setState({
     categories:this.props.categories,
   });
 }

 componentDidUpdate(){
  console.log(this.state.itemsPressed);
 }

 renderTabItem = ({ item,index }) => (
  <TouchableOpacity
   style={styles.category}
   key={index}
   onPress={() => this.togglePressed(item)}
  >
   <Card center 
    style={[styles.card,{backgroundColor: 
          this.isItemPressed(item) 
          ? item.color 
          : 'gray' 
     }]}>
     <Image source={item.icon} style={styles.categoryIcon}/>
   </Card>
   <Text size={12} center style={styles.categoryName} 
     medium color='black'
    >
    {item.name.toLowerCase()}
   </Text>
 </TouchableOpacity>
 );

renderTab(){
  const {categories} = this.state;
  return (
    <FlatList
    horizontal = {true}
    pagingEnabled = {true}
    scrollEnabled = {true}
    showsHorizontalScrollIndicator={false}
    scrollEventThrottle={16}
    snapToAlignment='center'
    data={categories}
    keyExtractor={(item) => `${item.id}`}
    renderItem={this.renderTabItem}
   />
 )
}
  render() {
    return (
       <ScrollView>
        {this.renderTab()}
       </ScrollView>
   );
  }
 }

我期待视觉上的变化,但我无法重新渲染 renderTab()。

谢谢!

最佳答案

您的 FlatList 具有属性 category 作为数据源,因此它仅在检测到 category 发生变化时才重新呈现单元格属性(property)。但是,您的代码仅更改 itemsPressed,因此不会重新呈现任何单元格。

您可以通过在 extraData 属性中指定 FlatList 来监听 state.itemsPressed 的变化:

extraData={this.state.itemsPressed}

关于javascript - View 在 onPress 后不重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56396507/

相关文章:

java - 我如何在opengl中画一个半圆

sqlite - 如何使用 react-native-sqlite-storage 将多行插入到表中?

android-studio - 如何配置 react-native expo 应用程序以在 android Studio 中运行?

css - react native :Styles overriding each other and container goes out of position

javascript - Angularjs 指令不起作用 "Unexpected token"

javascript - 传单 geojson 不会显示标记

javascript - Angularfire $loaded().then(从这里返回一些东西)

javascript - 我可以在加载由 jquery 附加的 iframe 后调用函数吗?

react-native - 如何禁止RN的WebView跳转到浏览器?

xcode - 错误无法构建 iOS 项目。我们运行了 "xcodebuild"命令,但它以错误代码 65 退出