如何将数据从一个React Native组件共享到另一组件 [英] How to share data from one react native component to another component

查看:96
本文介绍了如何将数据从一个React Native组件共享到另一组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组成部分地址",我正在使用google-places-autocomplete获取地址.之后,我提取了所需的数据(例如国家/地区,邮政编码等).现在,我想将此数据传输到主要组件"中.对于在哪里被调用.在地址组件中,我使用过useState()来存储数据.

 从"react-native"导入{View,StyleSheet,TextInput};从"react-native-google-places-autocomplete"导入{GooglePlacesAutocomplete};从"react-native"导入{};从"../constants/Colors"导入颜色;让地方= [];const地址=(属性)=>{const [place,setPlace] = useState();const [postalCode,setPostalCode] = useState();const [country,setCountry] = useState();const [state,setState] = useState();const [city,setCity] = useState();const setCountryHandler = {value)=> {setCountry(值)}const setPostalCodeHandler =(value)=> {setPostalCode(值)}const setCityHandler =(value)=> {setCity(value);}const setStateHandler =(value)=> {setState(值)}返回 (<查看样式= {{弹性:1,justifyContent:中心",alignItems:中心",marginVertical:10,}}><查看style = {styles.search}>< GooglePlacesAutocomplete占位符=地址"onPress = {{data,details = null)=> {让地址= details.address_components;让address1 = [];for(令i = 0; i< 1; i ++){为(让我输入地址){address1 = address [i] .types;对于(让j在地址1中){if(address1 [j] ==="sublocality"){places.push(address [i] .long_name);}}}setPlace(places);地方= [];}为(让我输入地址){address1 = address [i] .types;对于(让j在地址1中){if(address1 [j] ==="locality"){setCityHandler(address [i] .long_name);}}}为(让我输入地址){address1 = address [i] .types;对于(让j在地址1中){if(address1 [j] ==="administrative_area_level_1"){setState(address [i] .long_name);}}}为(让我输入地址){address1 = address [i] .types;对于(让j在地址1中){如果(address1 [j] ===国家"){setCountry(address [i] .long_name);}}}为(让我输入地址){address1 = address [i] .types;对于(让j在地址1中){如果(address1 [j] ===邮政编码"){setPostalCode(address [i] .long_name);}}}}}enablePoweredByContainer = {false}disableScroll = {false}fetchDetails = {true}查询= {{键:"#############################",语言:"en",}}样式= {{textInputContainer:{宽度:"100%",},}}/></View><查看style = {{justifyContent:"center",alignItems:"center",width:"80%"}}><查看样式= {styles.container}>< TextInput占位符="city";defaultValue = {city} onChangeText = {setCityHandler}/></View><查看样式= {styles.container}>< TextInput占位符="state";defaultValue = {state} onChangeText = {setStateHandler}/></View><查看样式= {styles.container}>< TextInput占位符=国家";defaultValue = {country} onChangeText = {setCountryHandler}/></View><查看样式= {styles.container}>< TextInput占位符="pincode"defaultValue = {postalCode} onChangeText = {setPostalCodeHandler}/></View></View></View>);};const styles = StyleSheet.create({容器: {marginVertical:10,宽度:"100%",paddingVertical:8,paddingHorizo​​ntal:8,borderColor:Colors.accent,borderWidth:1borderRadius:6backgroundColor:"white",},搜索:{marginBottom:10,宽度:"80%",borderColor:Colors.accent,borderWidth:1borderRadius:6backgroundColor:"white",}});导出默认地址; 

这是我的代码,我想将数据=城市,州,邮政编码,国家/地区转移到另一个组件中

解决方案

要将数据传输到另一个组件,该组件将需要是地址组件的子组件,这样子组件将接收地址组件状态为道具.

这就是人们使用Redux的原因,Redux创建容器并将您的所有状态存储在该容器中,然后您项目中的任何组件都可以访问它. https://react-redux.js.org/

但是,如果您的组件不相关,并且您不想使用redux,那么有一种方法可以做到这一点:通过异步存储将状态值保存到存储中.

https://github.com/react-native-async-storage/async-storage

,然后通过AsyncStorage在主组件中检索这些值.

i have a component "Address" were i am using google-places-autocomplete for getting address.After that i extract the needed data (such as Country,postal code etc). And now i want to transfer this data into the "Main Component" for where the is getting called. In Address Component, i have used useState() to store data.

import { View, StyleSheet, TextInput } from "react-native";
import { GooglePlacesAutocomplete } from "react-native-google-places-autocomplete";
import {  } from "react-native";
import Colors from "../constants/Colors";

let places = [];
const Address = (props) => {
  const [place, setPlace] = useState();
  const [postalCode, setPostalCode] = useState();
  const [country, setCountry] = useState();
  const [state, setState] = useState();
  const [city, setCity] = useState();

  const setCountryHandler=(value)=>{
    setCountry(value)
  }
  const setPostalCodeHandler=(value)=>{
    setPostalCode(value)
  }
  const setCityHandler=(value)=>{
    setCity(value);
  }
  const setStateHandler=(value)=>{
    setState(value)
  }
      

  return (
    <View style={{
      flex: 1,
      justifyContent: "center",
      alignItems: "center",
      marginVertical: 10,
    }}>
    <View
      style={styles.search}
    >
      <GooglePlacesAutocomplete
      placeholder="Address"
        onPress={(data,details=null)=>{
          let address = details.address_components;
          let address1 = [];
          for (let i = 0; i < 1; i++) {
            for (let i in address) {
              address1 = address[i].types;
              for (let j in address1) {
                if (address1[j] === "sublocality") {
                  places.push(address[i].long_name);
                }
              }
            }
            setPlace(places);
            places = [];
          }
          for (let i in address) {
            address1 = address[i].types;
            for (let j in address1) {
              if (address1[j] === "locality") {
                setCityHandler(address[i].long_name);
              }
            }
          }
          for (let i in address) {
            address1 = address[i].types;
            for (let j in address1) {
              if (address1[j] === "administrative_area_level_1") {
                setState(address[i].long_name);
              }
            }
          }
          for (let i in address) {
            address1 = address[i].types;
            for (let j in address1) {
              if (address1[j] === "country") {
                setCountry(address[i].long_name);
              }
            }
          }
          for (let i in address) {
            address1 = address[i].types;
            for (let j in address1) {
              if (address1[j] === "postal_code") {
                setPostalCode(address[i].long_name);
              }
            }
          }
        }}

        enablePoweredByContainer={false}
        disableScroll={false}
        fetchDetails={true}
        
        query={{
          key: "#############################",
          language: "en",
        }}
        styles={{
          textInputContainer: {
            width: "100%",
          },
        }}
      />
      </View>
      <View
        style={{ justifyContent: "center", alignItems: "center", width: "80%" }}
      >
        <View style={styles.container}>
          <TextInput placeholder="city" defaultValue={city} onChangeText={setCityHandler}/>
        </View>
        <View style={styles.container}>
          <TextInput placeholder="state" defaultValue={state} onChangeText={setStateHandler}/>
        </View>
        <View style={styles.container}>
          <TextInput placeholder="country" defaultValue={country} onChangeText={setCountryHandler} />
        </View>
        <View style={styles.container}>
          <TextInput placeholder="pincode" defaultValue={postalCode} onChangeText={setPostalCodeHandler}/>
        </View>
      </View>
    
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    marginVertical: 10,
    width: "100%",
    paddingVertical: 8,
    paddingHorizontal: 8,
    borderColor: Colors.accent,
    borderWidth: 1,
    borderRadius: 6,
    backgroundColor: "white",
  },
  search:{
    marginBottom:10,
    width: "80%",
    borderColor: Colors.accent,
    borderWidth: 1,
    borderRadius: 6,
    backgroundColor: "white",
  }
});

export default Address;

here's my code and i want to transfer data =city,state,postalcode,country into another component

解决方案

To transfer data , to another component , that Component will need to be the Child Component of your Address Component, in this way child component will receive Address Component states as props.

That's why people use Redux, which creates container and stores all your states in that container, which then can be accessed by any component in your project. https://react-redux.js.org/

But if your components are not related, and you don't want to use redux , then there is one way to do this is, that you save your state value to the storage via Async Storage.

https://github.com/react-native-async-storage/async-storage

and then retrieve those values in Main Component via AsyncStorage.

这篇关于如何将数据从一个React Native组件共享到另一组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆