简体   繁体   中英

Pass dynamic value to react native Modal View from flatList Item

I have a FlatList like... <FlatList data={data} keyExtractor={(item, index) => index.toString()}renderItem={({item,index}) =>(<NewView id={item.id} index={index}/>) }/> Now for render Item const NewView = ({id, index}) =>{return(<TouchablOpacity onPress={()=> openModal()}> <Text>{id}</Text></TouchableOpacity><Modal animationType='fade' transparent={true}visible={userOptionShowModal}onRequestClose={() =>setUserOptionShowModal(false)}}><Text>{?? ==>id}</Text></Modal>); } const NewView = ({id, index}) =>{return(<TouchablOpacity onPress={()=> openModal()}> <Text>{id}</Text></TouchableOpacity><Modal animationType='fade' transparent={true}visible={userOptionShowModal}onRequestClose={() =>setUserOptionShowModal(false)}}><Text>{?? ==>id}</Text></Modal>); } Now when i want to show modal on Pressing each flatlist item, its working but when Pressing one flatlist item showing the modal but in the modal item i cannot show the index or id or any dynamic value passed (how?) of that particular flatListItem... Please help how to achieve it?

You can achieve this behavior in many ways. One of the easiest way is to create a state that holds this information, then on modal close, you reset its value.

First, add this useState:

const [passedData, setPassedData] = useState({});

Then when you call the onPress, add all the info you need:

<TouchablOpacity onPress={()=> openModal({id, index})}>...</TouchablOpacity>

PS: openModal({id, index}) is same as openModal({id: id, index: index})

Then in your openModal function, add this:

const openModal = ({id, index}) => {
...
setPassedData({id, index})
}

Then you can access it in your modal (Don't forget to reset the passed data onCloseRequest or anytime you close the modal):

<Modal
  animationType="fade"
  transparent={true}
  visible={userOptionShowModal}
  onRequestClose={() =>{
  setUserOptionShowModal(false)
  setPassedData({})
 }}>
  <Text>id : {passedData.id}, index: {passedData.index}</Text>
</Modal>

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