Ошибка форматирования React Native / Firebase

1

Проблема. Я создаю очень простое приложение, которое позволит пользователям загружать сообщения в firebase, а затем приложение будет отображать все сообщения на firebase. Когда я добавил код FlatList для отображения сообщений в Firebase, у меня появилась ошибка (нижняя часть вопроса). Мне бы очень хотелось помочь исправить эту ошибку, и я понятия не имею, что вызвало ее.

Код

import React, { Component } from 'react';
import { StyleSheet, Text, View, Image, TextInput, ScrollView, TouchableHighlight, Button, FlatList } from 'react-native';
import { Font } from 'expo';
import * as firebase from 'firebase';



const firebaseConfig = {
  apiKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXX",
  authDomain: "candidtwo.firebaseapp.com",
  databaseURL: "https://candidtwo.firebaseio.com",
  storageBucket: "candidtwo.appspot.com",
};

const firebaseApp = firebase.initializeApp(firebaseConfig);

var fontLoaded = false;

var ref = firebase.database().ref('posts');

var newPostRef = ref.push();

export default class App extends React.Component {

  state = {
    fontLoaded: false,
  };



  componentDidMount() {
      Expo.Font.loadAsync({
        'JosefinSans-Regular.ttf': require('./JosefinSans-Regular.ttf'),
      });
 }
  constructor(props) {
    super(props);
    this.state = { postInput: ""}
  }

 render() {
    return (
      <View style={styles.container}>
        <View style={styles.button}>
          <View style={{width: 1, height: 30, backgroundColor: '#e8e8e8'}} />
          <Button
            onPress={() => this.setState({ fontLoaded: true })}
            title="Press Me To Load the App After 15 Seconds!"
            color="#fe8200"
            accessibilityLabel="Wait 15 seconds and then press me to load the font!"
          />
        </View>

        {this.state.fontLoaded ? (
          <View style={styles.container}>
            <Text style={{ fontFamily: 'JosefinSans-Regular.ttf', fontSize: 16 }}>
                Whats on your mind? Create a post!
            </Text>  

            <TextInput
                 style={{height:40, width: 320, borderColor: '#303030', borderWidth: 1}}
                 onChangeText={(postInput)=>this.setState({postInput})}
                 value={this.state.postInput}    
             />


    <Button
      onPress={() => {
        newPostRef.set({ content:this.state.postInput });
        this.setState({ postInput: "Your post was succsesfully uploaded! :)" })    
      }}               
      title="                              +                              "
      color="#fe8200"
    />

{/*var path = newPostRef.toString(); */}

            <ScrollView>
               <View style={{width: 1, height: 6, backgroundColor: '#e8e8e8'}} />
               <View style={{width: 350, height: 250, backgroundColor: '#1daff1',  alignItems: 'center', justifyContent: 'center',    borderRadius: 10, paddingLeft: 10, paddingRight:10}} >
         <Text style={{ fontFamily: 'JosefinSans-Regular.ttf', fontSize: 22, color: '#ffffff', textAlign: 'center'}}>
                    Why do android phones have higher inital quality than apple phones, but apple phones have a more consistent amount of quality throughout their years?
                </Text>
            </View>
               <View style={{width: 350, height: 40, borderRadius: 10, backgroundColor: '#147aa8', flexDirection: 'row',paddingLeft:5}} >
            <Image source={require('./CandidtwoImages/unlove.png')} />
            <Text style={{ fontFamily: 'JosefinSans-Regular.ttf', fontSize: 22, color: '#ffffff', paddingRight: 5, paddingTop:5}}>
                    3
                    </Text>
            <Image source={require('./CandidtwoImages/undislike.png')} />
            <Text style={{ fontFamily: 'JosefinSans-Regular.ttf', fontSize: 22, color: '#ffffff', paddingRight: 5, paddingTop:5}}>
                    1
                    </Text>
            <Image source={require('./CandidtwoImages/comments.png')} />
            <Text style={{ fontFamily: 'JosefinSans-Regular.ttf', fontSize: 22, color: '#ffffff', paddingRight: 5, paddingTop:5}}>
                    8
                    </Text>
        </View>
               <View style={{width: 1, height: 6, backgroundColor: '#e8e8e8'}} />
               <View style={{width: 35, height: 25, backgroundColor: '#147c41', borderRadius: 10}} />
               <View style={{width: 35, height: 4, backgroundColor: '#0f582d', borderRadius: 10}} />
               <View style={{width: 1, height: 6, backgroundColor: '#e8e8e8'}} />
           <View style={{width: 1, height: 6, backgroundColor: '#e8e8e8'}} />
               <View style={{width: 35, height: 25, backgroundColor: '#9dcd46', borderRadius: 10}} />
               <View style={{width: 35, height: 4, backgroundColor: '#6c8f31', borderRadius: 10}} />
               <View style={{width: 1, height: 6, backgroundColor: '#e8e8e8'}} />
           <View style={{width: 1, height: 6, backgroundColor: '#e8e8e8'}} />
               <View style={{width: 35, height: 25, backgroundColor: '#d3832e', borderRadius: 10}} />
               <View style={{width: 35, height: 4, backgroundColor: '#935b1e', borderRadius: 10}} />
               <View style={{width: 1, height: 6, backgroundColor: '#e8e8e8'}} />





     <FlatList>
        data={ref}
    renderItem={
        ({item}) => 
<View style={{width: 1, height: 6, backgroundColor: '#e8e8e8'}} />
           {/*Error happened here*/}    <View style={{width: 350, height: 250, backgroundColor: '#1daff1',  alignItems: 'center', justifyContent: 'center',    borderRadius: 10, paddingLeft: 10, paddingRight:10}}>
         <Text style={{ fontFamily: 'JosefinSans-Regular.ttf', fontSize: 22, color: '#ffffff', textAlign: 'center'}}>
                    {item.content}
                </Text>
            </View>
               <View style={{width: 350, height: 40, borderRadius: 10, backgroundColor: '#147aa8', flexDirection: 'row',paddingLeft:5}} >
            <Image source={require('./CandidtwoImages/unlove.png')} />
            <Text style={{ fontFamily: 'JosefinSans-Regular.ttf', fontSize: 22, color: '#ffffff', paddingRight: 5, paddingTop:5}}>
                    3
                    </Text>
            <Image source={require('./CandidtwoImages/undislike.png')} />
            <Text style={{ fontFamily: 'JosefinSans-Regular.ttf', fontSize: 22, color: '#ffffff', paddingRight: 5, paddingTop:5}}>
                    1
                    </Text>
            <Image source={require('./CandidtwoImages/comments.png')} />
            <Text style={{ fontFamily: 'JosefinSans-Regular.ttf', fontSize: 22, color: '#ffffff', paddingRight: 5, paddingTop:5}}>
                    8
                    </Text>
        </View>
               <View style={{width: 1, height: 6, backgroundColor: '#e8e8e8'}} />

    </FlatList>
        </ScrollView>
      </View>) : (null) }
      </View>
    );
  }
}





const styles = StyleSheet.create({
  container: {
    flex: 8,
    backgroundColor: '#e8e8e8',
    alignItems: 'center'
  },
  button: {
    flex: 1,
    backgroundColor: '#e8e8e8',
    alignItems: 'center'
  },
});

Ошибка неизвестна: смежные элементы JSX должны быть обернуты в тег-приложение (121:15)

Теги:
firebase
react-native

1 ответ

0
Лучший ответ

Проблема заключается в том, что при рендеринге компонента/группы для FlatList вам необходимо заключить все компоненты в этом рендере с родительским View, следовательно, "обертывание их в закрывающий тег". Всякий раз, когда у вас есть несколько View рядом с eachother, вы ДОЛЖНЫ вложить их в родительский View, возьмите это как правило большого пальца вперед. НАПРИМЕР

<View>
    <View />
    <View />
</View>

Теперь для вашей проблемы, вы захотите добавить View здесь

({item}) =>
     <View> //HERE

а затем закройте его в конце. Кроме того, вы не закрыли FlatList декларацию компонента FlatList, так что это также должно быть в конце этой части. renderItem ваша поддержка renderItem должна выглядеть так:

     renderItem={
                ({item}) =>
                        <View>
                            <View style={{width: 350, height: 250, backgroundColor: '#1daff1',  alignItems: 'center', justifyContent: 'center', borderRadius: 10, paddingLeft: 10, paddingRight:10}}>
                                <Text style={{ fontFamily: 'JosefinSans-Regular.ttf', fontSize: 22, color: '#ffffff', textAlign: 'center'}}>
                                    {item.content}
                                </Text>
                            </View>

                            <View style={{width: 350, height: 40, borderRadius: 10, backgroundColor: '#147aa8', flexDirection: 'row',paddingLeft:5}} >
                                <Image source={require('./CandidtwoImages/unlove.png')} />
                                <Text style={{ fontFamily: 'JosefinSans-Regular.ttf', fontSize: 22, color: '#ffffff', paddingRight: 5, paddingTop:5}}>
                                    3
                                </Text>
                                <Image source={require('./CandidtwoImages/undislike.png')} />
                                <Text style={{ fontFamily: 'JosefinSans-Regular.ttf', fontSize: 22, color: '#ffffff', paddingRight: 5, paddingTop:5}}>
                                    1
                                </Text>
                                <Image source={require('./CandidtwoImages/comments.png')} />
                                <Text style={{ fontFamily: 'JosefinSans-Regular.ttf', fontSize: 22, color: '#ffffff', paddingRight: 5, paddingTop:5}}>
                                    8
                                </Text>
                            </View>
                            <View style={{width: 1, height: 6, backgroundColor: '#e8e8e8'}} />
                        </View>
                }>

Обратите внимание, что вы также должны выполнять большинство своих стилей в этом родительском представлении, но на данный момент это решение должно работать. Вы часто увидите в учебниках styles.container, и это обычно то, что есть, контейнер всех компонентов подзадачи.

  • 0
    Спасибо, это исправило ошибку!

Ещё вопросы

Сообщество Overcoder
Наверх
Меню