在反应原生自定义button中进行组件的条件呈现

我是一位老程序员,学习使用react-native。

我有麻烦,因为我似乎无法有效地利用组件的条件渲染。 我的目标是有条件地加载这个button。

这是一个奇怪的问题,我花了整整一天的时间来解决这个问题,我在一个应用程序的场景中使用了renderIf技术, 它的工作非常完美 。 但是,当我在这个组件中使用它时,它立即崩溃,抛出一个NSException。

我已经使用了terminal命令npm install render-if –save来安装完美的场景,但不适合这个组件。

任何帮助将非常感激,任何build议的替代方法也将不胜感激。

GeneralButton.js

'use strict'; import React, { Component } from 'react'; import { StyleSheet, TouchableHighlight, View, Text, Dimensions, Platform, } from 'react-native'; import renderIf from 'render-if'; class GeneralButton extends Component { constructor(props) { super(props); this.state = { render: true } } getWidth(){ let width, percent; if (this.props.percent == true) { let screenWidth = Dimensions.get('window').width; width = (screenWidth / 100) * this.props.width; return width; } else { percent = false; width = this.props.width != null ? this.props.width : 300; return width; } } render() { return ( {renderIf(this.state.render)( <TouchableHighlight underlayColor='rgba(255, 255, 255, 0.2)' onPress={this.props.onPress}> <View style={styles.button} width={this.getWidth()}> <Text style={styles.buttonText}> {this.props.text} </Text> </View> </TouchableHighlight> )} ); } } const styles = StyleSheet.create({ button: { height: 44, borderColor: 'rgba(255, 255, 255, 0.8)', borderWidth: StyleSheet.hairlineWidth, paddingTop: 5, paddingBottom: 5, paddingLeft: 10, paddingRight: 10, alignItems: 'center', justifyContent: 'center', }, buttonText: { color: 'white', ...Platform.select({ ios: { fontFamily: 'OpenSans-Light', }, android: { fontFamily: 'opensanslight', }, }) }, }); module.exports = GeneralButton; 

在React中,组件渲染函数返回一个组件实例。 将View的渲染内容包裹起来。 在你的情况下,没有必要使用renderIf ,你可以使用内联,如果:

 render() { return ( <View> {this.state.render && <TouchableHighlight underlayColor='rgba(255, 255, 255, 0.2)' onPress={this.props.onPress}> <View style={styles.button} width={this.getWidth()}> <Text style={styles.buttonText}> {this.props.text} </Text> </View> </TouchableHighlight> } </View> ) }