gpt4 book ai didi

javascript - 在无状态组件中使用 Flatlist 响应 native 导航

转载 作者:行者123 更新时间:2023-11-29 20:55:36 31 4
gpt4 key购买 nike

我正在尝试创建无状态组件来显示平面列表,但我在导航方面遇到了困难。

这是我的“主要”app.js,精简版:

import React from 'react';
import { AppRegistry, FlatList, ActivityIndicator, Text, View, Image, StyleSheet } from 'react-native';
import { StackNavigator } from 'react-navigation'
import Strip from '../components/Strip'

export default class FetchData extends React.Component {

constructor(props){
super(props);
this.state ={ isLoading: true}
}

componentDidMount(){
...
}


render(){
if(this.state.isLoading){
...
}
return (
<View>
<Strip props={this.state.dataSource.strips} />
</View>
)
}
}

这是组件:

import React from 'react';
import { FlatList, Text, View, Image, StyleSheet, TouchableOpacity } from 'react-native';

renderItem = ({item}) => (
<TouchableOpacity onPress={() => this.props.navigation.navigate('Details')} >
<View style={{width: 136}}>
...
<Text>some text</Text>
</View>
</TouchableOpacity>
);

const Strip = (props) => {
return Object.keys(props).map(function(key, i) {
return Object.keys(props[key]).map((strips, i) => {
var strip = props[key][strips];
return(
<View>
<Text>{strip.title}</Text>
<FlatList horizontal
data={strip.someobjects}
renderItem={({item}) => this.renderItem(item)}
/>
</View>
)
});
})
}

export default Strip;

列表已显示,但当然,当我触摸某个项目时,出现“undefined is not an object (evaluating '_this.props.navigation')”错误。

我知道我不能在无状态组件上使用 this.props.navigation.navigate 但我只是不明白如何通过无状态组件中的平面列表传递导航 Prop 。

它必须非常简单,例如使用 navigate('Details') 并将 const { navigate } = this.props.navigation; 放在某处。但是在哪里呢?

最佳答案

不是从 Strip 组件进行 navigate,而是为 Strip 提供一个 onPress 处理程序并从那里导航。如果 FetchDataStackNavigator 的一部分,那么您可以轻松地从该组件导航

考虑下面的例子

...
export default class FetchData extends React.Component {
...
handleOnPress = () => {
this.props.navigation.navigate('Details')
}

render() {
if(this.state.isLoading){
...
}
return (
<View>
<Strip
props={this.state.dataSource.strips}
onPress={this.handleOnPress}
/>
</View>
);
}
}

Strip组件中,可以绑定(bind)onPress处理程序

 const Strip = (props) => {
renderItem = ({item}) => (
<TouchableOpacity onPress={props.onPress} >
<View style={{width: 136}}>
...
<Text>some text</Text>
</View>
</TouchableOpacity>
);

return Object.keys(props).map(function(key, i) {
return Object.keys(props[key]).map((strips, i) => {
var strip = props[key][strips];
return(
<View>
<Text>{strip.title}</Text>
<FlatList horizontal
data={strip.someobjects}
renderItem={({item}) => renderItem(item)}
/>
</View>
)
});
})
}

希望这会有所帮助!

关于javascript - 在无状态组件中使用 Flatlist 响应 native 导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49495321/

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