如何在React Native中呈现对象?

3
我正在使用React Native开发一个与Firebase链接的简单待办事项应用程序。我有一个类,其中包含几个方法。根据我在线搜索到的信息,似乎是渲染函数中的输出相关问题。但我检查了我的方法,无法确定确切的问题。以下是我的类:enter image description here
class ToDo_React extends Component {
  constructor(props) {
    super(props);
  var myFirebaseRef = new Firebase(' ');
  this.itemsRef = myFirebaseRef.child('items');

  this.state = {
    newTodo: '',
    todoSource: new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2})
  };

  this.items = [];
}
componentDidMount() {
  // When a todo is added
  this.itemsRef.on('child_added', (dataSnapshot) => {
    this.items.push({id: dataSnapshot.key(), text: dataSnapshot.val()});
    this.setState({
      todoSource: this.state.todoSource.cloneWithRows(this.items)
    });
  });
  this.itemsRef.on('child_removed', (dataSnapshot) => {
      this.items = this.items.filter((x) => x.id !== dataSnapshot.key());
      this.setState({
        todoSource: this.state.todoSource.cloneWithRows(this.items)
      });
  });
}
    addTodo() {
  if (this.state.newTodo !== '') {
    this.itemsRef.push({
      todo: this.state.newTodo
    });
    this.setState({
      newTodo : ''
    });
  }
}
    removeTodo(rowData) {
  this.itemsRef.child(rowData.id).remove();
}
render() { return (
<View style={styles.appContainer}>
  <View style={styles.titleView}>
    <Text style={styles.titleText}>
      My Todos
    </Text>
  </View>



<View style={styles.inputcontainer}>
    <TextInput style={styles.input} onChangeText={(text) => this.setState({newTodo: text})} value={this.state.newTodo}/>
    <TouchableHighlight
      style={styles.button}
      onPress={() => this.addTodo()}
      underlayColor='#dddddd'>
      <Text style={styles.btnText}>Add!</Text>
    </TouchableHighlight>
  </View>
  <ListView
    dataSource={this.state.todoSource}
    renderRow={this.renderRow.bind(this)} />
</View>
);
}
renderRow(rowData) {
return (
<TouchableHighlight
underlayColor='#dddddd'
onPress={() => this.removeTodo(rowData)}>
<View>
<View style={styles.row}>
  <Text style={styles.todoText}>{rowData.text}</Text>
</View>
<View style={styles.separator} />
</View>
</TouchableHighlight>
);
}
}
1个回答

3
问题出在你的renderRow方法中,你渲染了以下内容:
<Text style={styles.todoText}>{rowData.text}</Text>

在这里,您将对象作为Text元素的子元素进行传递,而不是字符串。因为您在此处将对象设置在数据存储中的text键下:
this.items.push({id: dataSnapshot.key(), text: dataSnapshot.val()});

请注意,此处的val()是指您已推送到Firebase实例的对象的引用(请参阅Firebase文档):
this.itemsRef.push({
  todo: this.state.newTodo
});

因此,你可能想要做的就是只推送this.state.newTodo而不是一个对象。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接