在我的React Native应用程序中,我的app.js中设置了以下路由:
export default class App extends Component {
render() {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen
name="Home"
component={ItemListing}
/>
<Stack.Screen
name="Details"
component={ItemImageDetails}
/>
</Stack.Navigator>
</NavigationContainer>
)
}
}
我有一个ItemListing组件,该组件具有多个ItemImage组件,在按下时应通过传入唯一ID导航到Details页面,该页面是ItemImageDetails组件。这些都是用打字稿写的。
ItemListing这样将导航道具传递给ItemImage:
import { NavigationScreenProp } from 'react-navigation'
...
interface ItemListingProps {
navigation: NavigationScreenProp<any,any>
}
export default class ItemListing extends Component<ItemListingProps,ItemListingState> {
constructor (props: ItemListingProps) {
super(props)
this.state = {
results: [],
searchTerm: ""
}
}
...
render() {
return (
<>
<View>
{this.state.results.map((result,index) =>
<ItemImage
navigation={this.props.navigation}
imageMetadata={result.data[0]}
imageUrl={result.links[0].href}
key={index}
/>
)}
</View>
</>
)
}
}
ItemImage写为:
import { NavigationScreenProp } from 'react-navigation'
...
interface ItemImageProps {
navigation: NavigationScreenProp<any,any>
imageMetadata: ImageMetadata
imageUrl: string
}
export default class ItemImage extends Component<ItemImageProps,{}> {
constructor (props: ItemImageProps) {
super(props)
}
render() {
return (
<>
<TouchableOpacity
onPress={() =>
this.props.navigation.navigate('Details', {
id: this.props.imageMetadata.id
})
}
>
</TouchableOpacity>
</>
)
}
}
ItemImageDetails组件如下:
interface ItemImageDetailsProps {
id: string
}
export default class ItemImageDetails extends Component<ItemImageDetailsProps, {}> {
constructor (props: ItemImageDetailsProps) {
super(props)
}
...
render() {
return (
<>
<Text>THIS IS THE DETAILS PAGE</Text>
<Text>{this.props.id}</Text>
...
</>
)
}
}
但是,Item.ImageDetails的props中的id在console.log中显示为“ undefined”。没有错误,项目可以正确构建。成功浏览到“详细信息”页面,并且ItemImage组件中的id正确,它似乎在导航道具中传递不正确
答案 0 :(得分:1)
道具界面错误。导航道具是按导航和路线组成的。内部路由有一个名为params的属性,因此如果要访问id,则必须去那里。另外,我建议输入您的路线,这样可以避免这类问题https://reactnavigation.org/docs/typescript
interface ItemImageDetailsProps {
navigate: any;
route: any;
}
export default class ItemImageDetails extends Component<ItemImageDetailsProps, {}> {
constructor (props: ItemImageDetailsProps) {
super(props)
}
...
render() {
return (
<>
<Text>THIS IS THE DETAILS PAGE</Text>
<Text>{this.props.route.params.id}</Text>
...
</>
)
}
}
答案 1 :(得分:0)
您可以简单地在ItemImageDetail中获得此ID,如下所示:
const id = this.props.navigation.getParam('id', null);