简体   繁体   English

React Native:从功能组件导出功能

[英]React Native: Exporting a function from a functional component

Issue:问题:

  1. I'm trying to figure out how to export a function that is called "addPostCode" from the functional component "ContractHandler".我试图弄清楚如何从功能组件“ContractHandler”中导出一个名为“addPostCode”的函数。

  2. I want to use "addPostCode" in an other functional component called "RentalDetailScreen" so that when I navigate to the next page it will trigger the "addPostCode" and store the state of "postCode" in "ContractHandler".我想在另一个名为“RentalDetailScreen”的功能组件中使用“addPostCode”,以便当我导航到下一页时,它将触发“addPostCode”并将“postCode”的状态存储在“ContractHandler”中。

This is the "ContractHandler.js":这是“ContractHandler.js”:

import React, { useState } from 'react';

const ContractHandler = () => {

  const [postCode, setPostCode] = useState();

  const addPostCode = (data) => {
    setPostCode(data)
    console.log(postCode)
  };

  return(
    <View>
      <Text></Text>
    </View>
  )

}

export default ContractHandler;

These are parts of the RentalDetailScreen.js where I navigate to the next page and want to trigger the "addPostCode"-function and send the "postCode"-value to the "ContractHandler.js".这些是 RentalDetailScreen.js 的一部分,我导航到下一页并希望触发“addPostCode”函数并将“postCode”值发送到“ContractHandler.js”。

This is the import:这是导入:

import { addPostCode } from '../../database/ContractHandler';

This is the navigation with the "addPostCode"-function.这是带有“addPostCode”功能的导航。

<TouchableOpacity onPress={() => { navigation.navigate('SecurityDetail'); addPostCode(postCode); }}>
  <View style={slider.buttonStyle}>
    <Text style={slider.textStyle}>Neste</Text>
    <Ionicons name='ios-arrow-forward'style={slider.iconStyle} />
  </View>
</TouchableOpacity>

"postCode" is just a variable that is given a value from a TextInput. “postCode”只是一个从 TextInput 获得值的变量。

If I'm not being clear enough please let me know and I will try to explain better :)如果我不够清楚,请告诉我,我会尽力解释得更好:)

The components' own state cannot be set from outside (technically you can solve it but this is not the right way).不能从外部设置组件自己的状态(从技术上讲,您可以解决它,但这不是正确的方法)。 If you wanna share state between components, use global state manager (redux) or Context or if the components are siblings, just use their common parent to store the state.如果您想在组件之间共享状态,请使用全局状态管理器 (redux) 或Context或者如果组件是兄弟组件,只需使用它们的公共父级来存储状态。

There are two ways to solve this.有两种方法可以解决这个问题。 You can use a state manager like redux or you have to pass the function as props from component to component.您可以使用像 redux 这样的状态管理器,或者您必须将函数作为道具从组件传递到组件。 Personally I would use redux because it makes it simpler to share state between components.我个人会使用 redux,因为它可以更简单地在组件之间共享状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM