【问题标题】:Select an item from dropdown and use that value in another component in React native从下拉列表中选择一个项目并在 React native 的另一个组件中使用该值
【发布时间】:2022-01-14 10:27:26
【问题描述】:

我只是想做类似的事情(当用户选择一个项目,然后导航到另一个组件):

     const handleValueChange=(itemValue, itemIndex) =>setTypeValue(itemValue)
    
       const onPress = () => {
    
            try{
              
              const topic = "Plant/type";
              ...
              navigation.navigate('Air')
             
            }catch(err){
              console.log(err)
            }  
            
          }
   return (
         <Picker
                  selectedValue={typeValue}
                  onValueChange={handleValueChange}
                  style={{ top: '21%', height: 50, width: 150 }}/> 

       <TouchableOpacity
                          style={styles.button}
                          onPress={()=> onPress()}
                        />
)

通常,当我们想在两个组件之间传递值时,我们会使用 props:

<AirScreen typeofPlant={typeValue} />

但在这种情况下,我不知道如何在不调用 AirScreen 的情况下做到这一点

【问题讨论】:

标签: javascript reactjs react-native ecmascript-6 react-props


【解决方案1】:

只需这样做:

navigation.navigate('RouteName', { /* params go here */ })

您可能需要阅读以下文档: https://reactnavigation.org/docs/params/

【讨论】:

    【解决方案2】:

    你可以这样做:

    const onPress = () => {
        try{
            const topic = "Plant/type";
            ...
            navigation.navigate('Air', {newTopic: topic}) //you can pass another value by separating with comma
        }catch(err){
            console.log(err)
        }     
    }
    

    然后您可以在下一个屏幕中获取相同的值,例如:

    function NextScreen({ route, navigation }) {
        const topic = route.params.newTopic
    }
    

    希望这对你有用。

    【讨论】:

    • 感谢您的回复,这就是我为解决它所做的工作
    猜你喜欢
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-23
    相关资源
    最近更新 更多