代码之家  ›  专栏  ›  技术社区  ›  Rohan Kulkarni

按React Native按钮时不返回组件

  •  1
  • Rohan Kulkarni  · 技术社区  · 7 年前

    我是react原生框架的初学者。我正在构建一个示例移动应用程序。我被困在最基本的一步。 我试图在单击事件时调用“getbusinessnews()”函数,该函数将返回一个组件。但由于某种原因,它没有回来。 我已经仔细检查了组件的路径及其正确性。 甚至函数内部定义的console.log也会显示出来。 我附上代码,谢谢你的帮助。 提前谢谢你。

    import React, {Component} from 'react';
    import {Text,View,TouchableOpacity} from 'react-native';        
    import BusinessNews from '../News/BusinessNews';
    class categories extends Component{ 
       render(){
          return(
              <View>
                 <TouchableOpacity onPress={this.getBusinessNews.bind(this)}>
                    <Text>Business News</Text>
                 </TouchableOpacity>
              </View>
           );
       }
    
       getBusinessNews(){ 
           console.log(1);
           return(      
             <BusinessNews />
           );
        }
    
       export default categories;
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   RIYAJ KHAN    7 年前

    从返回组件 event handler/listener 渲染将不起作用。 相反地 state update 决定组件是否 BusinessNews 是否会渲染。

    应该是这样的。

    构造器

    constructor() {
      this.state = {
        showBusiness: false//initially set to false
      }
    }
    

    获取商业新闻

    getBusinessNews() {
      this.setState({showBusiness: true})//set to true to show BusinessNews
    }
    

    提供

    render() {
    
      render() {
        return (
          <View>
            <TouchableOpacity
              onPress={this
              .getBusinessNews
              .bind(this)}>
              {this.state.showBusiness ===true && <BusinessNews/>}//check boolean true 
              <Text>Business News</Text>
            </TouchableOpacity>
          </View>
        );
      }
    
    }
    
        2
  •  1
  •   Nirmalsinh Rathod    7 年前

    单击时可以返回组件。因为您必须返回组件 渲染() 只有。您需要更改逻辑以呈现组件。

    你可以打电话 <BusinessNews /> 在某处 render() 添加组件。