反应本机Newsapi搜索字词

时间:2020-11-04 10:17:02

标签: react-native

我需要按标题实施搜索字词, 这是我要存档的内容 https://blog.jscrambler.com/add-a-search-bar-using-hooks-and-flatlist-in-react-native/。我正在尝试解决这个问题,但无法解决 Search.js

Import React, { useState, useEffect } from "react";
import {
    StyleSheet,
    StatusBar,
    Text,
    View,
    FlatList,
    Button,
    TextInput,
} from "react-native";
import NewsCards from "./NewsCards";
import Colors from "../constants/Colors";
import Env from "../constants/Env";
import { useNavigation } from "@react-navigation/native";
import { Appbar } from "react-native-paper";

const search = () => {
    const [newsData, setNewsData] = useState();
    const [errorMessage, setErrorMessage] = useState();
    const navigation = useNavigation();
    const [searchValue, setSearchValue] = useState("");
    const [searchResults, setSearchResults] = useState(null);

    const searchHandler = async () => {
        try {
            const search = `http://newsapi.org/v2/top-headlines?country=us&q=${searchValue}&apiKey=${Env.NEWS_API_KEY}`;
            const response = await fetch(search);
            const responseJson = await response.json();
            if (response.ok) {
                setSearchResults(responseJson.articles);
            } else setErrorMessage(responseJson.message);
        } catch (error) {
            console.log("Error", error);
            setErrorMessage(error.message);
        }
    };

    useEffect(() => {
        searchHandler();
    }, []);

    const load = async () => {
        try {
            const newsApi = `http://newsapi.org/v2/top-headlines?country=us&apiKey=${Env.NEWS_API_KEY}`;
            const response = await fetch(newsApi);
            const responseJson = await response.json();

            if (response.ok) {
                setNewsData(responseJson.articles);
            } else setErrorMessage(responseJson.message);
        } catch (error) {
            console.log("Error", error);
            setErrorMessage(error.message);
        }
    };

    useEffect(() => {
        load();
    }, []);

    const renderItem = ({ item }) => (
        <NewsCards
            title={item.title}
            description={item.description}
            urlToImage={item.urlToImage}
            content={item.content}
        />
    );

    return (
        <View style={styles.container}>
            <StatusBar backgroundColor={Colors.primary} barStyle="default" />
            <Appbar>
                <Button title="Go Back" onPress={() => navigation.goBack()} />

                <View>
                    <Button
                        title="us"
                        onPress={() => {
                            /* 1. Navigate to the Details route with params */
                            navigation.navigate("main");
                        }}
                    />

                    <Button
                        title="gb"
                        onPress={() => {
                            /* 1. Navigate to the Details route with params */
                            navigation.navigate("mainGB");
                        }}
                    ></Button>
                </View>
            </Appbar>
            <TextInput
                placeholder="Search"
                onChange={(e) => setSearchValue(e.target.value)}
                onKeyDown={searchHandler}
                style={styles.formField}
                placeholderTextColor={"#888888"}
            />
            <View style={styles.header}>Top News US</View>
            {searchResults ? (
                <FlatList
                    data={newsData}
                    renderItem={renderItem}
                    keyExtractor={(item) => item.publishedAt}
                />
            ) : (
                errorMessage && <Text style={styles.errMsg}>Error: {errorMessage}</Text>
            )}
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: Colors.primary,
    },
    header: {
        height: 50,
        backgroundColor: Colors.primary,
        alignItems: "center",
    },
    title: {
        fontSize: 28,
        color: "white",
    },
    errMsg: {
        fontSize: 18,
        justifyContent: "center",
        alignItems: "center",
        color: "white",
    },
});

export default search;

这是卡片组件的NewsCard.js

import React, { useState } from "react";
import { StyleSheet, Linking, TouchableOpacity } from "react-native";
import { Avatar, Button, Card, Title, Paragraph } from "react-native-paper";
import { useNavigation } from "@react-navigation/native";

const NewsCards = ({
    srcName,
    author,
    title,
    description,
    urlToImage,
    url,
    publishedAt,
    content,
}) => {
    const navigation = useNavigation();
    return (
        <>
            <Card style={styles.newsCards}>
                <Card.Content>
                    <Title>{title}</Title>
                    <Card.Cover source={{ uri: urlToImage }} />
                    <Paragraph>{description}</Paragraph>
                </Card.Content>
                <Card.Actions>
                    <TouchableOpacity
                        style={styles.button}
                        title="More"
                        onPress={() => {
                            /* 1. Navigate to the Details route with params */
                            navigation.navigate("NewsDetails", {
                                urlToImage,
                                content,
                                title,
                            });
                        }}
                    />
                </Card.Actions>
            </Card>
        </>
    );
};

const styles = StyleSheet.create({
    newsCards: {
        marginHorizontal: 10,
        marginVertical: 10,
        borderRadius: 25,
    },
    button: {
        width: 100,
        height: 100,
        backgroundColor: "red",
    },
});

export default NewsCards;

   

0 个答案:

没有答案
相关问题