【问题标题】:Conditional rendering of components in a react-native custom buttonreact-native 自定义按钮中组件的条件渲染
【发布时间】:2017-07-03 14:48:20
【问题描述】:

我是一个正在学习使用 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;

【问题讨论】:

    标签: javascript node.js reactjs react-native


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-20
      • 2020-12-28
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多