简体   繁体   English

如何在反应本机中单击平面列表项时将值传递给模态并显示模态

[英]How to pass a value to modal and show modal when click on flatlist item in react native

i want to pass a value from activity screen to modal screen.我想将一个值从活动屏幕传递到模式屏幕。 I am trying to open a screen when click on flatlist item an dpass value of item to modal,but it shows my detail before rendering modal screen,Here is my activity screen:-我试图在单击 flatlist 项目时打开一个屏幕,将项目的 dpass 值传递给模态,但它在呈现模态屏幕之前显示了我的详细信息,这是我的活动屏幕:-

  <FlatList
                  data={this.state.myListDataSource}
                  renderItem={this._renderItem}
                  showsHorizontalScrollIndicator={false}
                  showsVerticalScrollIndicator={false}
                  keyExtractor={({item,index}) => item+index}
                  refreshControl={
                    <RefreshControl
                      refreshing={this.state.isRefreshing}
                      onRefresh={this.pullToRefresh}
                    />
                  }
                />

<ListProducts
                  modalVisibility={this.state.listModalVisibility}
                  closeModal={() => 
 this.setState({listModalVisibility:false})}
                  listName={this.state.listName}
                  listId={this.state.listId}
              />

handleListItemPress = (item) => {    
  this.setState({
    listModalVisibility:true,
    listName : item.name,
    listId : item.list_id
  })
  showMessage('List Item : '+item.listId)

} }

 _renderItem = ({item}) => {
return(
  <TouchableOpacity onPress={() => this.handleListItemPress(item)}>
    <View >
      <View>
        <View style={{flexDirection:'row',marginBottom:2}}>
          <ImageView 
            image={item.pictures[0]}
            style={[{marginRight:2},styles.imageStyle]}
          />
          <ImageView 
            image={item.pictures[1]}
            style={[{marginLeft:2},styles.imageStyle]} 
          />
        </View>
        <View style={{flexDirection:'row',marginTop:2}}>
          <ImageView 
            style={[{marginRight:2},styles.imageStyle]}
            image={item.pictures[2]}
          />
          <ImageView 
            image={item.pictures[3]}
            style={[{marginLeft:2},styles.imageStyle]}
          />
        </View>
      </View>
      <View>
        <TextViewNonClickable 
          textViewText={item.name}

        />
        <TextViewNonClickable 
          textViewText={item.description}

        />
      </View>
      <Icon
        name = 'more-vertical'
        type = 'feather'
        color = {color.colorWhite}
        iconStyle={{padding:8}}
        containerStyle = {{position:'absolute',top:8,right:8}}
        onPress = {() => {
          showMessage('Options')
        }}
      />
    </View>
  </TouchableOpacity>
)}

This is my modal screen where i want to get list item id or name.But that screen shows details on the screen rather than rendering modal screen .这是我的模式屏幕,我想在其中获取列表项 ID 或名称。但该屏幕在屏幕上显示详细信息,而不是呈现模式屏幕。 Here is my modal screen :-这是我的模态屏幕:-

export default class ListProducts extends Component {

  constructor(props){
super(props)
this.state={
  products : [],
  refreshing : false,
  listId : 256,
  listName : props.name
}
  }

_renderProducts = ({item}) => { _renderProducts = ({item}) => {

return(
  <Product
      image={item.image}
      name={item.name}
      price={item.price}
      discountedPrice={item.discounted_price}
      quantityAdded={item.quantity_added}
      productId={item.product_id}
      stock={item.stock}
  />
)
  }

  render() {

const {modalVisibility,closeModal,listName,listId} = this.props;

return (
  <Modal 
    animationIn='bounceInRight'
    animationOut='bounceOutRight'
    isVisible={modalVisibility}
    onBackButtonPress={closeModal}
  >
    <View style={{flex:1,backgroundColor:color.colorWhite}}>
        <Header
            placement='left'
            leftComponent={
        <FlatList
            data={this.state.products}
            renderItem={this._renderProducts}
            keyExtractor={(item,index) => item+index}
            refreshControl={
              <RefreshControl
                  refreshing={this.state.refreshing}
                  onRefresh={this.pullToRefresh}
              />
          }
          numColumns={3}
          style={{paddingLeft:2,paddingRight:2}}
        />
    </View>
  </Modal>
)
  }
}

I'm actually using 'Dialog' from 'react-native-simple-dialogs' for popup.我实际上是在使用“react-native-simple-dialogs”中的“Dialog”来弹出窗口。 It works better for me than 'Modal', but i think the logic is the same.它比“模态”更适合我,但我认为逻辑是相同的。 Here is a simplified example of a edit email popup that works for me:这是一个适用于我的编辑电子邮件弹出窗口的简化示例:

import React from 'react';
import { StyleSheet, View, TextInput } from 'react-native';
import { Button, Text } from 'native-base';
import { Dialog } from 'react-native-simple-dialogs';


export default class EditEmailPopup extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      isModalVisible: this.props.isModalVisible,
    };
  }

  componentWillUpdate() {
    this.state.isModalVisible = this.props.isModalVisible;
  }

  _updateEmailAndCloseDialog() {
    // update some data...
    this._onCloseDialog();
  }

  _onCloseDialog() {
    this.setState({ isModalVisible: false});
    this.props.client();   //this is a function transfered from parent that controls the visibility of the dialog.
  }

  render() {
    return (
      <View>
        <Dialog
          visible={this.state.isModalVisible}
          onTouchOutside={() => this._onCloseDialog()}
        >
          <View>
            <Text style={styles.text}>{'Update Email text'}</Text>
            <View style={styles.popupButtons}>
              <Button
                transparent
                style={styles.cancelButton}
                onPress={() => this._onCloseDialog()}
              >
                <Text> {'cancel'} </Text>
              </Button>

              <Button
                style={styles.okButton}
                onPress={() => this._updateEmailAndCloseDialog()}
              >
                <Text> {'ok'} </Text>
              </Button>
            </View>
          </View>
        </Dialog>
      </View>
    );
  }
}

Here is how i add my Dialog in the parent view:这是我如何在父视图中添加我的对话框:

{this.state.emailModalVisibility ? (
   <EditEmailPopup
     isModalVisible={this.state.emailModalVisibility}
     client={this.afterClosePopup}
   />
 ) : null}

while this.state.emailModalVisibility initiated in the constructor in state as 'false'.而 this.state.emailModalVisibility 在构造函数中启动,状态为“false”。

function written in parent:写在父级的函数:

_afterClosePopup = () => {
    this.setState({
      emailModalVisibility: false
    });
  };

and binded in the constructor so 'this' will belong to parent:并绑定在构造函数中,因此“this”将属于父级:

 constructor(props) {
    super(props);
    this.afterClosePopup = this._afterClosePopup.bind(this);
    this.state = {
      emailModalVisibility: false
    };
  }

Step 1: pass props from modal to class.第 1 步:将道具从模态传递到类。 In modal like:在模态中:

this.props.setItem(“sunny”)

Step 2: Get that props in class in render method where modal initialised.第 2 步:在模态初始化的渲染方法中获取类中的道具。

<ModalName SetItem={item => console.log(item)} \>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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