繁体   English   中英

在React-Native中按下按钮不返回组件

[英]Not returning a component on button press in React-Native

我是本机框架的初学者。 我正在构建一个示例移动应用程序。 而且我坚持最基本的步骤。 我试图在点击事件上调用“ 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;

event handler/listener返回组件以进行渲染将不起作用。 取而代之的是进行state update以确定组件BusinessNews是否将呈现。

它应该这样做。

建设者

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

getBusinessNews

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>
    );
  }

}

您可以点击返回组件。 因为您必须仅返回render()中的 component。 您需要更改逻辑以渲染组件。

您可以在render()中的某个位置调用<BusinessNews />以添加组件。

暂无
暂无

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

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