React Native中的条件组件

时间:2017-04-28 17:55:38

标签: javascript react-native react-native-ios

我刚开始使用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;

2 个答案:

答案 0 :(得分:4)

如果我理解你的问题,你想知道如果属性存在,如何只展示一些东西?这样的事情应该有效。

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

答案 1 :(得分:2)

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

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

然后在您的render()中,您将<Text style={styles.profileText2}>{item.education}</Text>替换为{this.renderEducationField()}