React Native - 在图标上渲染组件

Posted

技术标签:

【中文标题】React Native - 在图标上渲染组件【英文标题】:React Native - render a component onClick on an Icon 【发布时间】:2021-08-25 10:52:00 【问题描述】:

我的应用程序的一部分有一个“图标”。当我“单击”图标时,父组件的状态变为“true”,我想要一个新的“组件”来呈现“我是一个新组件”。我在下面尝试这样,调试器上没有显示错误。 Icon 是我正在导入的图像组件。这是代码。

这是父组件

   import React, Component from 'react';
   import View from 'react-native';
   import Icon from '../ui/Icon';


   type HomeSceneState = 
    calendarState:boolean
  


  class HomeScene extends Component<HomeSceneState> 
        state = 
           calendarState:false
          

        openCalendar = () => 
           console.log("open calendar")
           this.setState(
           calendarState : true
          )

         

       render() 
          return (
     
            <View style=marginBottom: spacing.double,
                   backgroundColor:"black", flexDirection:"row"
                   >
              <View>
              <Icon onPress = () => this.openCalendar() />
              this.calendarState ? <Casie/> : null 
             </View>

           </View>
    
          );
        
       

      export default HomeScene;

子组件如下所示

   class Casie extends Component<CalendarProps> 

      render() 
        return (
          <View>
           I am a new Component
        </View>
        );
      
    
  
    export default Casie;

【问题讨论】:

你可以使用 react navigation 来导航页面 你能举个例子吗? 【参考方案1】:

&lt;Calendar/&gt; 替换为您的子组件名称&lt;Casie/&gt;(在您的情况下)。当状态发生变化时,您似乎没有渲染您的子组件。

【讨论】:

【参考方案2】:

在您的父组件中,您导入反应原生导航。 在您可以使用 useNavigation 导航页面之后。对不起我的英语。

import  useNavigation  from '@react-navigation/native'

class HomeScene extends Component<HomeSceneState> 
    state = 
       calendarState:false
      

    openCalendar = () => 
       console.log("open calendar")
       navigation.navigate('Casie')
     

   render() 
      return (...)
       
    
   

  export default HomeScene;

【讨论】:

以上是关于React Native - 在图标上渲染组件的主要内容,如果未能解决你的问题,请参考以下文章

React-native Navigation 添加汉堡包图标

React Native - 状态改变但组件没有重新渲染

React native - 在渲染应用程序组件之前从异步存储中获取数据

ScrollView 在 react-native 中渲染没有数据的更新组件?

在 React Native 中更新渲染组件

为啥组件在状态更改后不重新渲染。在 react-native 函数组件中