问题
I am using react native and expo. I have some json data on the screen (similator iOS) such as
A
Acompany
B
Bcompany
here A is symbol and Acompany is name
When user click on it it should redirect to another screen such as (Stock.js) and pass the symbol
as well? How can I redirect it to another screen when user click on it and send this data (symbol
)?
My code:
import React, { useState, useEffect } from "react";
import {
StyleSheet,
View,
TouchableWithoutFeedback,
Keyboard,
FlatList,
TextInput,
Button,
Text,
} from "react-native";
import { useStocksContext } from "../contexts/StocksContext";
import { scaleSize } from "../constants/Layout";
import { Ionicons } from "@expo/vector-icons";
import { ListItem } from "react-native";
export default function SearchScreen({ navigation }) {
const { ServerURL, addToWatchlist } = useStocksContext();
const [state, setState] = useState({
/* initial state here */
myListData: [],
});
const [search, setSearch] = useState("");
useEffect(() => {
renderWithData();
// FixMe: fetch symbol names from the servner and save in local SearchScreen state
}, []);
const updateSearch = (text) => {
setSearch(text);
};
renderWithData = () => {
return fetch("http://131.181.190.87:3001/all")
.then((res) => res.json())
.then((json) => {
setState({
isLoaded: true,
myListData: json,
});
setTimeout(() => {
console.log(state.myListData);
}, 10000);
});
};
let filteredItems = state.myListData.filter((item) => {
return (
item.symbol.toUpperCase().indexOf(search.toUpperCase()) !== -1 ||
item.name.indexOf(search) !== -1
);
});
let movies = filteredItems.map((val) => {
return (
<View key={val.symbol} style={styles.text}>
<Text style={styles.text}>{val.symbol}</Text>
<Text style={styles.text}>{val.name}</Text>
</View>
);
});
return (
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<View style={styles.container}>
<TextInput
style={styles.textinput}
placeholder="Search here"
placeholderTextColor="white"
value={search}
onChangeText={(text) => updateSearch(text)}
/>
<Text>csdn</Text>
<View style={styles.text}>{movies}</View>
</View>
</TouchableWithoutFeedback>
);
}
const styles = StyleSheet.create({
textinput: {
color: "white",
height: "20",
fontSize: 18,
},
text: {
color: "white",
backgroundColor: "black",
},
flatstuff: {
color: "white",
},
// use scaleSize(x) to adjust sizes for small/large screens
});
回答1:
You have to use a navigation library to support the navigation of your app You can refer the react-native-navigation here
Once you have basic stack setup like below
<Stack.Screen name="Home" component={SearchScreen} />
<Stack.Screen name="Details" component={DetailsScreen} />
You can navigate like below
navigation.navigate('Details',{text:'123'})
You can access the params like below from the details screen
const { text } = route.params;
来源:https://stackoverflow.com/questions/62274571/how-to-redirect-to-another-page-when-user-click-on-json-data-on-screen-and-pass