如何避免文本字符串必须在<text>组件中呈现问题?

时间:2018-12-18 15:34:10

标签: reactjs react-native react-redux

我收到以下错误:

  

未捕获的错误:始终违反:文本字符串必须在   一个组件。此错误位于:RCTView中的RCTView中   在C中的RCTView中的RCTView中的v中的p

代码:

import React from 'react';
import { StyleSheet, Text, View, TextInput, Button } from 'react-native';

export default class App extends React.Component {
  state = {
    placeName: "",
    places: []
  }
  placeNameChangedHandler = val => {
    this.setState({
      placeName: val
    });
  };

  placeSubmitHandler = () => {
    if (this.state.placeName.trim() === "") {
      return;
    }
    this.setState(prevState => {
      return {
        places: prevState.places.concat(prevState.placeName)
      };
    });
  };

  render() {
    const placesOutput = this.state.places.map((place,i) => (
      <Text key={i}> 
       </Text>
    ));
    return (
      <View style={styles.container}>
        <View style={styles.inputContainer}>
          <TextInput
            placeholder="Enter Your Name?"
            defaultValue={this.state.placeName}
            onChangeText={this.placeNameChangedHandler}
            style={styles.PlaceInput}

          ></TextInput>
          <Button
            title="Add"
            style={styles.placeButton}
            onPress={this.placeSubmitHandler} />
        </View>
        <View>  </View>
      </View>

    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 26,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: "flex-start"
  },
  inputContainer: {
    // flex:1,
    flexDirection: "row",
    justifyContent: "space-between",
    width: "100%"
  },
  PlaceInput: {
    width: "70%"
  },
  placeButton: {
    width: "30%"
  }
});

2 个答案:

答案 0 :(得分:0)

我认为它与map()函数的使用有关,如果将其用于JSX,则应显式返回(不支持JSX的隐式返回):

render() {
  const placesOutput = this.state.places.map((place,i) => {
    return(<Text key={i}> </Text>);
 })

但是我真的看不到您对这个placesOutput变量在做什么?

答案 1 :(得分:0)

实际上,组件的自动关闭对我来说很好,如下所示:

<View/>

代替:

 <View> </View>

<TextInput
            placeholder="Enter Your Name?"
            defaultValue={this.state.placeName}
            onChangeText={this.placeNameChangedHandler}
            style={styles.PlaceInput}
          /> 

代替:

  <TextInput
            placeholder="Enter Your Name?"
            defaultValue={this.state.placeName}
            onChangeText={this.placeNameChangedHandler}
            style={styles.PlaceInput}
          ></TextInput>