React Native 中的条件组件

Conditional Components in React Native

我是 React Native 的新手,我想知道创建一个条件组件的最佳方法是什么,该组件将在用户数据有字段时显示,而在没有时隐藏。在此示例中使用教育。

import React, { Component } from 'react';
import { StyleSheet, Image, TouchableOpacity } from 'react-native';
import { Container, Content, Button, Icon, View, DeckSwiper, Card, CardItem, Thumbnail, Text, Left, Body} from 'native-base';

import styles from './style';

const cards = [
    {
        _id: 1,
        name: 'John Doe',
        age: 30,
        education: 'State University',
        occupation: 'Programmer',
        company: 'Acme Inc.',
        image: require('img.jpg')
    },
    {
        _id: 2,
        name: 'Jane Doe',
        age: 30,
        education: 'State University',
        occupation: 'Programmer',
        company: 'Acme Inc.',
        image: require('img.jpg')
    },
    {
        _id: 2,
        name: 'Jane Doe',
        age: 30,
        education: 'State University',
        occupation: 'Programmer',
        company: 'Acme Inc.',
        image: require('img.jpg')
    },
];

export default class Cards extends Component {

    constructor(){
        super();
        this.state = {
            showEdu: true
        }
    }

    render() {
        let edu = this.state.showEdu ? this.props.education : '';
        return (
            <Container>
                <View>
                    <DeckSwiper
                        dataSource={cards}
                        renderItem={item =>
                            <Card style={{ elevation: 3 }}>
                                <CardItem cardBody>
                                    <Image style={styles.cardImg} source={item.image} />
                                </CardItem>
                                <CardItem>
                                    <Icon name="heart" style={{ color: '#ED4A6A' }} />
                                    <Content>
                                        <Text>{item.name}, {item.age}</Text>
                                        <Text style={styles.profileText2}>{item.occupation}, {item.company}</Text>
                                        <Text style={styles.profileText2}>{item.education}</Text>
                                    </Content>
                                </CardItem>
                            </Card>
                        }
                    />
                </View>
            </Container>
        );
    }
}

module.export = Cards;

看看你有什么教育意义,你可以写一个单独的方法,比如:

renderEducationField() {
  if (item.education !== '') {
    return (
      <Text style={styles.profileText2}>{item.education}</Text>
    )
  }
}

然后在你的 render() 中你会用 {this.renderEducationField()}

替换 <Text style={styles.profileText2}>{item.education}</Text>

如果我对你的问题理解正确,你想知道如何只在 属性 存在时显示某些内容?像这样的东西应该有用。

{ item.education &&
    <Text style={styles.profileText2}>{item.education}</Text>
}