[英]How to set condition inside prop based on state value in react native?
我正在使用组件<MapboxGL.UserLocation
获取当前用户坐标,并且在此组件中有一个道具onUpdate
,它获取用户的当前位置并将其传递给 function,我想要的是在调用 function 之前检查道具内state value if it is true or false and only if the state value true the function will be triggered, I have done the following but all times it call the function onUserLocationUpdate(location)
even if the state is false
<MapboxGL.UserLocation
renderMode="normal"
visible={true}
onUpdate={location => {
if (!isStartL) {
console.log("not start yet")
} else {
onUserLocationUpdate(location)
}
}}
/>
这是 state 我正在使用const [isStartL, setisStartL] = useState(false);
更新完整代码:
const app = ({ navigation }) => {
const [isStartL, setisStartL] = useState(false);
const onUserLocationUpdate = (location) => {
console.log(location);
}
const renderLocationInfo = () => {
if (!isStartL) {
return (<View style={styles.rcontainer}>
<Text style={styles.btn}>Press start when you are in the same location </Text>
<TouchableOpacity onPress={setisStartL(true)} >Start</TouchableOpacity>
</View>)
}
}
return (
<View style={styles.matchParent}>
<MapboxGL.MapView
surfaceView={true}
zoomLevel={15}
logoEnabled={false}
style={styles.matchParent}
>
<MapboxGL.UserLocation
renderMode="normal"
visible={true}
onUpdate={(location) => {
(!isStartL) ? console.log("not start yet") : onUserLocationUpdate(location)
}}
/>
<MapboxGL.Camera
followZoomLevel={17}
followUserMode={'normal'}
followUserLocation={true}
followZoomLevel={17}
animationDuration={1000}
/>
</MapboxGL.MapView>
{renderLocationInfo()}
</View>
)
}
请执行下列操作:
<MapboxGL.UserLocation
renderMode="normal"
visible={true}
onUpdate={(location) => {
(!isStartL) ? console.log("not start yet") : onUserLocationUpdate(location)
}}
/>
试试这样
<MapboxGL.UserLocation
renderMode="normal"
visible={true}
onUpdate={(location) => {
isStartL
? onUserLocationUpdate(location)
: console.log('not start yet');
}}
/>
一种方法是,在onUserLocationUpdate()
function 中移动 if 逻辑。
如果你的 state 是假的,就从它那里返回。 否则,执行其他步骤。
这样,您可以确保预期的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.