gpt4 book ai didi

javascript - 如何在 React Native 中渲染对象?

转载 作者:行者123 更新时间:2023-11-29 10:37:48 25 4
gpt4 key购买 nike

我正在开发一个使用 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>
);
}
}

最佳答案

问题出在您渲染的 renderRow 方法上:

<Text style={styles.todoText}>{rowData.text}</Text>

这里您传递的是一个对象作为 Text 元素的子元素而不是字符串。那是因为您要在此处的数据存储的 text 键下设置一个对象:

this.items.push({id: dataSnapshot.key(), text: dataSnapshot.val()});

请注意,此处的 val() 是对您已推送到此处的 firebase 实例的对象的引用(请参阅 firebase docs ):

this.itemsRef.push({
todo: this.state.newTodo
});

所以你可能想在这里做的只是推送 this.state.newTodo 而不是一个对象。

关于javascript - 如何在 React Native 中渲染对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34013057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com