简体   繁体   中英

copyText from an array - expo react native

this is my code:

const Contact = ({ contact }) => {
  const [inputValue, setInputValue] = React.useState("");

 const copyText = (text) => {
   Clipboard.setString(text);
    };
 return (
<View style={styles.contactCon}>
  <View style={styles.imgCon}>
    <View style={styles.placeholder}>
      <Text style={styles.txt}>{contact?.name[0]}</Text>
    </View>
  </View>
  <View style={styles.contactDat}>
    <Text style={styles.name}>{contact?.name}</Text>
    <Text style={styles.phoneNumber}>
    {contact?.phoneNumbers?.[0]?.number ?? 'No phone number'}
    </Text>
    <TouchableOpacity  onPress={copyText(contact?.phoneNumbers?.[0]?.number ?? 'No phone number')} >
    <Text style={styles.butao}>Copy</Text>
    </TouchableOpacity>
    
  </View>
</View>
 );
};

im trying to copy the number that is in the contact, but when i press the button 'copy', some random number is copied

What im doing wrong

Hard to say without looking at the array structure and more context ie is there one phone numbers array for everybody or is this array specific to each user?

What the above code is doing is copying the first number it finds in the array. Why is it random? Because there probably isn't any sorting on the array so as the data changes, so will the array.

However, if nothing I said above applies to you, try change the onPress to this: copyText(contact?.phoneNumbers[0]?.number - I think the structure of this is slightly wrong, the change I made was adding the square brackets before ?.

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