简体   繁体   English

如何在本机反应中将值从一个选项卡发送到另一个选项卡

[英]How to send value from one tab to another tab in react native

Here in my code I am making tree tabs, on first tabe there are two input fields and buttons.在我的代码中,我正在制作树形标签,在第一个标签上有两个输入字段和按钮。 Now after entering the value in input and on button click i have to send vale to oter tabs.现在在输入中输入值并单击按钮后,我必须将值发送到其他选项卡。 Like in in name field I am entering name "Abhi" and on button click this Abhi should reflect on Tab 2. Same like in Animal field, this Animal should reflect on third tab.就像在名称字段中一样,我正在输入名称“Abhi”,然后在按钮上单击此 Abhi 应反映在选项卡 2 中。与动物字段相同,此动物应反映在第三个选项卡上。 Please help请帮忙

 import * as React from 'react';
    import { View, StyleSheet, Dimensions,Text,TextInput,TouchableOpacity } from 'react-native';
    import { TabView, SceneMap } from 'react-native-tab-view';
     
    const FirstRoute = () => (
      <View style={[styles.scene, { backgroundColor: '#FFFFFF' }]} >
        <View  style={{}}>
        <Text style={{margin:15}}>Name </Text>
        <TextInput style={styles.input}
                   underlineColorAndroid = "transparent"
                   placeholder = "Name"
                   placeholderTextColor = "#9a73ef"
                   autoCapitalize = "none"
                   onChangeText={text => onChangeText(text)}
                  />
        <TouchableOpacity
                   style = {styles.submitButton}
                   onPress = {
                      () => this.Name()
                   }>
                   <Text style = {styles.submitButtonText}> Submit </Text>
                </TouchableOpacity>
                </View>
    
                <View style={{}}>
        <Text style={{margin:15}}> Favorite Animal  </Text>
        <TextInput style={styles.input}
                   underlineColorAndroid = "transparent"
                   placeholder = "Favorite Animal"
                   placeholderTextColor = "#9a73ef"
                   autoCapitalize = "none"
                   onChangeText={text => onChangeText(text)}
                  />
        <TouchableOpacity
                   style = {styles.submitButton}
                   onPress = {
                      () => this.Animal()
                   }>
                   <Text style = {styles.submitButtonText}> Submit </Text>
                </TouchableOpacity>
                </View>
    
      </View>
    );
     
    const SecondRoute = () => (
      <View style={[styles.scene, { backgroundColor: '#FFFFFF' }]} >
    <Text> {'Name' }</Text>
    </View>
    );
     
    const ThirdRoute = () => (
      <View style={[styles.scene, { backgroundColor: '#FFFFFF' }]} >
        <Text> {"Favorite Animal "}</Text>
      </View>
    );
    
    const initialLayout = { width: Dimensions.get('window').width };
     
    export default function TabViewExample() {
      const [index, setIndex] = React.useState(0);
      const [routes] = React.useState([
        { key: 'first', title: 'First' },
        { key: 'second', title: 'Second' },
        { key: 'third', title: 'Third' },
      ]);
     
      const renderScene = SceneMap({
        first: FirstRoute,
        second: SecondRoute,
        third:ThirdRoute
      });
     
      return (
        <TabView
          navigationState={{ index, routes }}
          renderScene={renderScene}
          onIndexChange={setIndex}
          initialLayout={initialLayout}
        />
      );
    }
     
    const styles = StyleSheet.create({
      scene: {
        flex: 1,
      },
      container: {
        paddingTop: 23
     },
     input: {
        margin: 15,
        height: 40,
        borderColor: '#7a42f4',
        borderWidth: 1
     },
     submitButton: {
        backgroundColor: '#65D370',
        padding: 10,
        margin: 15,
        height: 40,
     },
     submitButtonText:{
        color: 'white',
        alignSelf:'center',
        justifyContent:'center',
        borderRadius:20
    
      
     }
    });

Shortest answer, is try to use a state .最短的答案是尝试使用state Using states and passing the state from parent to child may be your best option.使用状态并将 state 从父母传递给孩子可能是您的最佳选择。 Here is one way you can go about it.这是您可以了解它的一种方法 go

1st in your TabViewExample add a useState() hook to keep the form data and change your renderScene() to a function, do not use SceneMap .第一个在您的TabViewExample中添加一个useState()挂钩以保留表单数据并将您的renderScene()更改为 function,不要使用 SceneMap Example:例子:

...
    const [name, setName] = React.useState(undefined);
      
        const renderScene = ({ route }) => {
          switch (route.key) {
            case "first":
              return <FirstRoute setName={setName} />;
            case "second":
              return <SecondRoute name={name} />;
            case "third":
              return <ThirdRoute />;
            default:
              <FirstRoute setName={setName} />;
          }
        };

(A) The reason for using renderScene() as function is explained with more detail on the "react-native-tab-view" documentation. (A) 使用renderScene()作为 function 的原因在“react-native-tab-view”文档中有更详细的解释。 In short when you need to pass props to components you should not use SceneMap() which you are using above instead turn renderScene into a function and use switch .简而言之,当您需要将道具传递给组件时,您不应使用上面使用的SceneMap() ,而是将 renderScene 转换为 function 并使用switch

(B) We only passed setName to the first component because that's what we'll be using. (B) 我们只将setName传递给第一个组件,因为这是我们将要使用的。

2nd - Make use of the props in your components. 2nd - 利用组件中的道具。 So now they'll look more or less like this:所以现在它们或多或少看起来像这样:

    const FirstRoute = props => (
       <View style={[styles.scene, { backgroundColor: "#FFFFFF" }]}>                                                                                   
         <View style={{}}>
           <Text style={{ margin: 15 }}>Name </Text>
           <TextInput
             style={styles.input}
             underlineColorAndroid="transparent"
             placeholder="Name"
             placeholderTextColor="#9a73ef"
             autoCapitalize="none"
             onChangeText={text => props.setName(text)}
           />
...

And for the SecondRoute:对于第二条路线:

const SecondRoute = props => (
   <View style={[styles.scene, { backgroundColor: "#FFFFFF" }]}>
     <Text> {props.name}</Text>
   </View>
 );

So now when you change the first Input in FirstRoute, the name state will automatically be updated, so when you go/swipe to page 2, you should see whatever you typed on the first TextInput on page 1.因此,现在当您更改 FirstRoute 中的第一个 Input 时, name state 将自动更新,因此当您转到/滑动到第 2 页时,您应该会看到您在第 1 页的第一个 TextInput 上键入的任何内容。

PS: this is just a brief explanation so I just gave you the essential idea behind sharing data across tabs/components. PS:这只是一个简短的解释,所以我只是为您提供了跨选项卡/组件共享数据的基本思想。 On your code you can create cleaner form handler functions and handler functions for those buttons.在您的代码中,您可以为这些按钮创建更简洁的表单处理函数和处理函数。 I could've done it, but I'll leave that job for you as it was not part of your initial question.我本可以做到的,但我会把这份工作留给你,因为这不是你最初问题的一部分。 Hope this helps and let me know if you need a more detailed/in-depth response.希望这会有所帮助,如果您需要更详细/深入的回复,请告诉我。

PS 2: If you use my current example don't click the buttons otherwise you'll get errors because you have no handler function, just type on the input and go to the second page to see the result. PS 2:如果您使用我当前的示例,请不要单击按钮,否则会出现错误,因为您没有处理程序 function,只需在输入中键入 go 即可查看结果。

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

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