我正在将标记渲染到react-native-map应用程序中。所以我在后端 API 中为每个标记定义了一个类型。现在我想使用自定义图标显示它们。
目前我单独渲染每种类型。像这样
//from API
this.setState({MyMarkers: (response.data)})
Type1mapMarkers = () => {
return this.state.MyMarkers.filter( report => report.type === 'type1').map((report) =>
<Marker
key={report.id}
coordinate={{ latitude: report.latitude, longitude:report.longitude }}
title={report.name}
description={report.info}
icon={require("../statics/icons/type1.png")}
>
<Image
source={require("../statics/icons/type1.png")}
style={{ width: 20, height: 20 }}
/>
</Marker >)
}
Type2mapMarkers = () => {
return this.state.MyMarkers.filter( report => report.type === 'type2').map((report) =>
<Marker
key={report.id}
coordinate={{ latitude: report.latitude, longitude:report.longitude }}
title={report.name}
icon={require("../statics/icons/type2.png")}
>
<Image
source={require("../statics/icons/type2.png")}
style={{ width: 20, height: 20 }}
/>
</Marker >)
}
render() {
return (
<SafeAreaView >
<View>
<MapView
...
>
{this.Type1mapMarkers()}
{this.Type2mapMarkers()}
</MapView>
</View>
</SafeAreaView>
);
}
有没有办法在渲染中使用 if 语句?我已经测试了一些选项但没有成功。有小费吗?我想要实现的目标是
this.setState({MyMarkers: (response.data)})
MapMarkers = () => {
return this.state.MyMarkers.map((report) =>
if (){
<Marker>
....
</Marker>}{
<Marker>
....
</Marker>}
}
render() {
return (
<SafeAreaView >
<View>
<MapView
...
>
{this.MapMarkers()}
</MapView>
</View>
</SafeAreaView>
);
}
我会使用直接的方法:
render() {
const { MyMarkers } = this.state
return <MapView>
{MyMarkers?.map( report =>
<Marker
...
icon={require(`../statics/icons/${report.type}.png` )}
>
<Image source={require(`../statics/icons/${report.type}.png`)} />
</Marker>)}
</MapView>
}
注意使用`
进行字符串插值