簡體   English   中英

React Native 平面列表

[英]React Native Flat List

我正在嘗試使用 React Native FlatList 循環通過獲取 API 響應的新聞頁面,該響應將從包含 web 視圖元素的模式加載。 一切似乎都運行良好,但每次我點擊新聞文章時,它總是循環遍歷所有文章並給我最后一篇文章而不是點擊的文章。 如果我 console.log(item.title) 它返回點擊的文章標題,但不加載它。 我什至將文章數據作為 state 傳遞,但我不確定我做錯了什么,請幫忙。 請忽略額外的代碼,因為我專注於在重構和刪除未使用的 CSS 之前確保它正常工作。 這是代碼。 如果您需要回購來發布鏈接,請告訴我。 提前致謝。

import React, { Component } from "react";
import { WebView } from "react-native-webview";
import {
  View,
  StyleSheet,
  Text,
  ActivityIndicator,
  Image,
  Button,
  Linking,
  TouchableOpacity,
  Modal
} from "react-native";
import { FlatList } from "react-native-gesture-handler";

export default class NewsPage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataSource: [],
      isLoading: true,
      modalVisible: false
    };
  }

  componentDidMount() {
    return fetch(
      "https://newsapi.org/v2/everything?q=empleos&language=es&apiKey=bc9471b0c90c4d1a8d41860292e59d6b"
    )
      .then(response => response.json())
      .then(responseJson => {
        this.setState(
          {
            isLoading: false,
            dataSource: responseJson.articles
          },
          function() {}
        );
      })
      .catch(error => {
        console.error(error);
      });
  }

  setModalVisible(articleData) {
    this.setState({
      modalVisible: true,
      modalArticleData: articleData
    });
  }

  closeModal = () => {
    this.setState({
      modalVisible: false,
      modalArticleData: {}
    });
  };

  render() {
    if (this.state.isLoading) {
      return (
        <View style={{ flex: 1, padding: 20 }}>
          <ActivityIndicator />
        </View>
      );
    }

    return (
      <View style={{ flex: 1, paddingTop: 20 }}>
        <FlatList
          data={this.state.dataSource}
          keyExtractor={({ id }, index) => id}
          renderItem={({ item }) => (
            <View style={styles.newsListContainer}>
              <Image
                style={styles.newsImage}
                source={{
                  uri:
                    item.urlToImage != null
                      ? item.urlToImage
                      : "../assets/icon.png"
                }}
              />
              <View style={styles.newsInfo}>
                <Text numberOfLines={2} style={styles.newsTitle}>
                  {item.title}
                </Text>
                <Text numberOfLines={3} style={styles.newsDescription}>
                  {item.description}
                </Text>
                <Text>{item.author}</Text>
              </View>
              <View style={styles.newsLink}>
                <Button
                  title="Leer"
                  onPress={() => {
                    console.log(item);
                    this.setModalVisible(item);
                  }}

                  // {Linking.openURL(item.url);}}
                />
              </View>
              <Modal
                animationType="slide"
                transparent={false}
                visible={this.state.modalVisible}
              >
                <View style={styles.newsHeader}>
                  <TouchableOpacity
                    onPress={() => {
                      this.closeModal();
                    }}
                  >
                    <Text style={styles.newsClose}>Cerrar</Text>
                  </TouchableOpacity>
                  <Text>{item.title}</Text>
                </View>
                <WebView
                  startInLoadingState={true}
                  source={{ uri: item.url }}
                  style={{ padding: 8 }}
                />
              </Modal>
            </View>
          )}
        />
      </View>
    );
  }
}

NewsPage.navigationOptions = {
  headerTitle: "Noticias en Español"
};

const styles = StyleSheet.create({
  mainBackgroundColor: {
    backgroundColor: "#007bff",
    padding: 8
  },
  mainBackground: {
    alignItems: "center",
    justifyContent: "center",
    flex: 1
  },
  textHeader: {
    backgroundColor: "#fff",
    marginTop: 16,
    fontSize: 32,
    padding: 8,
    borderRadius: 8,
    color: "#007bff"
  },
  firstText: {
    fontSize: 16,
    marginTop: 16,
    marginBottom: 0,
    color: "#fff"
  },
  phone: {
    marginTop: 16,
    color: "#fff"
  },
  secondText: {
    fontSize: 16,
    marginTop: 0,
    color: "#fff"
  },
  thirdText: {
    fontSize: 16,
    marginTop: 8,
    color: "#ffffff",
    textTransform: "uppercase",
    textAlign: "center",
    padding: 8,
    marginBottom: 12
  },
  firstButton: {
    marginBottom: 16
  },

  newsListContainer: {
    width: "100%",
    marginBottom: 4,
    padding: 4,
    flex: 1,
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between"
  },

  newsImage: {
    flexBasis: "25%",
    height: "100%"
  },

  newsInfo: {
    flexBasis: "55%",
    padding: 2,
    alignSelf: "flex-start"
  },

  newsLink: {
    flexBasis: "20%"
  },

  newsTitle: {
    fontSize: 20,
    color: "#000000",
    marginLeft: 8
  },

  newsDescription: {
    fontSize: 12,
    color: "efefef",
    marginLeft: 8
  },

  newsHeader: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    padding: 4
  },

  newsClose: {
    fontSize: 20,
    color: "red"
  }
});

在您的模態中,您正在使用

<Text>{item.title}</Text>

代替

<Text>{this.state.modalArticleData.title}</Text>

也為 WebView 組件做同樣的事情。

source={{ uri: this.state.modalArticleData.url }}

還有一件事:

  • 從 react-native 導入 Flatlist 而不是 react-native-gesture-handler

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM