首页 > 解决方案 > 反应原生的平面列表行的全局或静态状态

问题描述

是否有可能对于所有行Flatlist都有一个static state。我有一个Component我只想在Flatlist单击它时显示在 's 的一行上。当我点击其他行时,FlatlistComponent应该在上一行呈现,而是在当前点击的行上呈现。

2行平面列表

在这里,我有两行 Flatlist。我只想为单击的卡片视图或播放按钮呈现进度条。Flatlist所以我的逻辑是当我单击 Button 然后我以某种方式将 clicked行的 keyID 放在全局 state中,这只会呈现单击的 Card View 的进度条。不知何故喜欢这段代码:

{  GlobalState===this.props.key && (<ProgressBar />)}

作为平面列表中每一行渲染的检查器

标签: react-nativestaticstateglobalreact-native-flatlist

解决方案


我最终在组件和组件的道具中使用了全局变量。

在:renderItem_Flatlist

renderItem中的函数Flatlist

_play = () => {
    this.setState({ playState: "playing" });
    TrackPlayer.play();
    const thisplaying = this.props.item.Key;
    ProgressBar.setCurrentPlayer(thisplaying);//Here I call to put the Key of Item to the component's global variable
  };

在渲染中使用renderItem组件Flatlist

<ProgressBar PlayerKey={this.props.item.Key} />

在 Component{ ProgressBar.js} 中使用的 renderItem 中Flatlist

import React from "react";
import { View, Slider, Text} from "react-native";
import TrackPlayer, { ProgressComponent } from "react-native-track-player";
import { formatTime } from "./utils";
global.MineKey = null; //Here I used Global Variable
class ProgressBar extends ProgressComponent {
  static setCurrentPlayer = player => {
    global.MineKey = player;         //Setting global variable on every call from the cardview upon play
  };

  onSliderEditStart = () => {
    TrackPlayer.pause();
  };
  onSliderEditEnd = () => {
    TrackPlayer.play();
  };
  onSliderEditing = value => {
    TrackPlayer.seekTo(value);
  };

  render() {
    const position = formatTime(Math.floor(this.state.position));
    const duration = formatTime(Math.floor(this.state.duration));
    return global.MineKey == this.props.PlayerKey ? (  //If Global variable key is equal to the Key of RowItem of Flatlist
      <View style={{ flexDirection: "row",alignItems: "center", flex: 1,width: "100%"}}>
        <Text style={{ color: "white", alignSelf: "center" }}>{position}</Text>
        <Slider
          onTouchStart={this.onSliderEditStart}
          onTouchEnd={this.onSliderEditEnd}
          onValueChange={this.onSliderEditing}
          value={this.state.position}
          maximumValue={this.state.duration}
          maximumTrackTintColor="gray"
          minimumTrackTintColor="white"
          thumbTintColor="white"
          style={{
            flex: 1,
            alignSelf: "center"
          }}
        />
        <Text style={{ color: "white", alignSelf: "center" }}>{duration}</Text>
      </View>
    ) : null;
  }
}
module.exports = ProgressBar;

推荐阅读