多年来,我一直坚持这一想法,试图弄清楚当我按下每个渲染的FlatList项目时如何分别控制台记录每个Firebase Cloudstore文档ID。
我可以使用onPress={() =>{console.log(this.state.posts[0].key)}}
等来抓取某个键/ ID。但是我不知道如何分别抓取每个键/ ID。本质上,我只想要按下的touchableOpacity的文档ID。不只是[0]
屏幕截图位于应用布局的下方,因此您可以了解并获得代码示例
PostsLayout.js
export default class PostsLayout extends React.Component {
render() {
const {summary, stringTime, user} = this.props;
return (
<TouchableOpacity
style={styles.container}
onPress={this.props.onPress}
>
<PostsUser user={user}/>
<PostsSummary summary={summary}/>
<PostsDate time={stringTime}/>
</TouchableOpacity>
)
}
}
FlatListLayout.js
export default class FlatListLayout extends React.Component {
render() {
return (
<ScrollView >
<FlatList
data={this.props.data}
renderItem={({item}) => <PostsLayout {...item} onPress={this.props.onPress}/>}
/>
</ScrollView>
)
}
}
ScreenLayout.js
export default class ScreenLayout extends React.Component {
state = {
posts: []
}
db = firebase.firestore()
path = this.db.collection('usersData').doc(firebase.auth().currentUser.uid).collection("posts")
onCollectionUpdate = (querySnapshot) => {
const posts = [];
querySnapshot.forEach((doc) => {
const {summary, time, stringTime, user, userId} = doc.data();
posts.push({
key: doc.id, doc, summary,
time, stringTime, user, userId
});
});
this.setState({
posts
});
}
componentDidMount() {
const {currentUser} = firebase.auth();
this.setState({currentUser})
this.unsubscribe = this.path.onSnapshot(this.onCollectionUpdate)
}
componentWillUnmount() {
this.unsubscribe();
}
render() {
return (
<FlatListLayout
data={this.state.posts}
onPress={() => {console.log(this.state.posts[0].key)}}
/>
)
}
}
感谢您阅读本文档,请提供帮助:)
答案 0 :(得分:1)
因此,最简单的解决方法是从子级别的原始press事件发送一个函数自变量。 例如,PostsLayout具有主要的onPress,因此在此调用上仅发送回您需要的任何数据,每个组件将具有与该组件相关的特定数据。因为每个孩子的反应都是独一无二的。 PostsLayout.js
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
System.out.println(count());
}
}
FlatListLayout.js
export default class PostsLayout extends React.Component {
handleOnPress = () => {
const { onPress, index } = this.props;
if( typeof onPress === 'function') {
onPress(this.props, index); // here pass anything you want in the parent level, like even userm stringtime etc
}
}
render() {
const {summary, stringTime, user} = this.props;
return (
<TouchableOpacity
style={styles.container}
onPress={this.handleOnPress}
>
<PostsUser user={user}/>
<PostsSummary summary={summary}/>
<PostsDate time={stringTime}/>
</TouchableOpacity>
)
}
}
ScreenLayout.js
export default class FlatListLayout extends React.Component {
render() {
return (
<ScrollView >
<FlatList
data={this.props.data}
renderItem={({item, index }) => <PostsLayout {...item} index={index} onPress={this.props.onPress}/>}
/>
</ScrollView>
)
}
}
让我知道这是否没有道理:)