Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/react-native/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
React native React本机新闻API搜索词_React Native - Fatal编程技术网

React native React本机新闻API搜索词

React native React本机新闻API搜索词,react-native,React Native,我需要通过标题实现搜索词, 这是我想要存档的东西 . 我正试图解决这个问题,但我找不到解决办法 Search.js Import React, { useState, useEffect } from "react"; import { StyleSheet, StatusBar, Text, View, FlatList, Button, TextInput, } from "react-native&quo

我需要通过标题实现搜索词, 这是我想要存档的东西 . 我正试图解决这个问题,但我找不到解决办法 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;
Import React,{useState,useffect}来自“React”;
进口{
样式表,
状态栏,
文本,
看法
平面列表,
按钮
文本输入,
}从“反应本族语”;
从“/新闻卡”导入新闻卡;
从“./常量/颜色”导入颜色;
从“./constants/Env”导入环境;
从“@react-navigation/native”导入{useNavigation}”;
从“react native paper”导入{Appbar};
常量搜索=()=>{
const[newsData,setNewsData]=useState();
const[errorMessage,setErrorMessage]=useState();
const navigation=useNavigation();
常量[searchValue,setSearchValue]=useState(“”);
const[searchResults,setSearchResults]=useState(null);
const searchHandler=async()=>{
试一试{
常量搜索=`http://newsapi.org/v2/top-headlines?country=us&q=${searchValue}&apiKey=${Env.NEWS\u API\u KEY}`;
常量响应=等待获取(搜索);
const responseJson=wait response.json();
if(response.ok){
设置搜索结果(响应文章);
}else setErrorMessage(responseJson.message);
}捕获(错误){
console.log(“错误”,Error);
setErrorMessage(error.message);
}
};
useffect(()=>{
searchHandler();
}, []);
const load=async()=>{
试一试{
const newsApi=`http://newsapi.org/v2/top-headlines?country=us&apiKey=${Env.NEWS_API_KEY}`;
const response=等待获取(newsApi);
const responseJson=wait response.json();
if(response.ok){
setNewsData(responseJson.articles);
}else setErrorMessage(responseJson.message);
}捕获(错误){
console.log(“错误”,Error);
setErrorMessage(error.message);
}
};
useffect(()=>{
加载();
}, []);
常量renderItem=({item})=>(
);
返回(
navigation.goBack()}/>
{
/*1.使用参数导航到详细路线*/
导航。导航(“主”);
}}
/>
{
/*1.使用参数导航到详细路线*/
导航。导航(“mainGB”);
}}
>
setSearchValue(e.target.value)}
onKeyDown={searchHandler}
style={style.formField}
占位符文本颜色={“#888888”}
/>
美国头条新闻
{搜索结果(
项目.publishedAt}
/>
) : (
errorMessage&&Error:{errorMessage}
)}
);
};
const styles=StyleSheet.create({
容器:{
弹性:1,
背景颜色:Colors.primary,
},
标题:{
身高:50,
背景颜色:Colors.primary,
对齐项目:“中心”,
},
标题:{
尺寸:28,
颜色:“白色”,
},
错误消息:{
尺码:18,
辩护内容:“中心”,
对齐项目:“中心”,
颜色:“白色”,
},
});
导出默认搜索;
这是卡组件的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;

   
import React,{useState}来自“React”;
从“react native”导入{样式表,链接,TouchableOpacity};
从“react National paper”导入{化身、按钮、卡片、标题、段落};
从“@react-navigation/native”导入{useNavigation}”;
常量新闻卡=({
姓名,
作者
标题
描述
urlToImage,
网址,
出版,
内容,,
}) => {
const navigation=useNavigation();
返回(
{title}
{说明}
{
/*1.使用参数导航到详细路线*/
导航。导航(“新闻详情”{
urlToImage,
内容,,
标题
});
}}
/>
);
};
const styles=StyleSheet.create({
新闻卡:{
marginHorizontal:10,
玛吉:10,
边界半径:25,
},
按钮:{
宽度:100,
身高:100,
背景颜色:“红色”,
},
});
导出默认的新闻卡;

您能澄清一下您的问题吗?你应该明确你遇到的实际问题/困难