【问题标题】:React Native - render a component onClick on an IconReact Native - 在图标上渲染组件
【发布时间】: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 来导航页面
  • 你能举个例子吗?

标签: reactjs react-native components setstate


【解决方案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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-13
      • 2020-09-13
      • 1970-01-01
      • 2016-06-01
      • 1970-01-01
      • 2017-01-31
      相关资源
      最近更新 更多