简体   繁体   中英

How to convert string in parent to proptype.number for React child component?

I am sending latitude and longitude :

<ListItem
   title="Endereço"
   rightTitle={location ? location : '-'}
   hideChevron
   onPress={() => this.props.navigation.navigate('Maps', {latitude: latitude, longitude: longitude})}
 />

This sends ok, but the child component is waiting for a proptype.number while my parent is sending a string type.

How do I convert my props latitude and longitude to numbers?

You can use the built in JavaScript Number() function. Assuming the code you are showing is the parent, just wrap the string values in Number() :

<ListItem
   title="Endereço"
   rightTitle={location ? location : '-'}
   hideChevron
   onPress={() => this.props.navigation.navigate('Maps', {latitude: Number(latitude), longitude: Number(longitude)})}
 />

There are other ways to do this also, but this method has the advantage of clearly communicating your intention.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM