javascript - 在 react native 自定义按钮中有条件地呈现组件

标签 javascript node.js reactjs react-native

我是一个学习使用react-native的老程序员。

我遇到了麻烦,因为我似乎无法有效地利用组件的条件渲染。我的目标是有条件地加载此按钮。

这是一个奇怪的问题,我花了一整天的时间试图解决它,我在应用程序的一个场景中使用了 renderIf 技术并且它工作得很好。但是,当我在此组件中使用它时,它会立即崩溃, 抛出 NSException。

我已经使用终端命令 npm install render-if --save 来安装非常适合场景但不适用于此组件的包。

任何帮助将不胜感激,任何关于替代方法的建议也将不胜感激。

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,您可以使用 inline if:

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

关于javascript - 在 react native 自定义按钮中有条件地呈现组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44888545/

相关文章:

javascript - 使用 React-native modal 形成和设置适当的对话框或警告框的样式

node.js - 当我安装node.js时,它给了我一些错误。并且安装失败

node.js - 使用 Redis Cloud 和 Heroku 正确配置 Node session 存储

javascript - Meteor根据条件语句加载JS文件

javascript - window.location.href 在当前页面内插入新页面

javascript - 如何在jwplayer 6自动模式下找到质量的比特率值?

node.js - 如何调试 yeoman 应用程序?

reactjs - 具有远距离共享状态的 React 组件

javascript - 如何在 React 上设置具有撤消操作的初始状态?

javascript - 如何使用react路由链接将参数传递给组件