简体   繁体   English

如何在 React Native 中将道具传递给模态组件

[英]How to Pass Props to Modal Component in React Native

I need to pass Flatlist data to modal in react native.我需要在 React Native 中将 Flatlist 数据传递给模态。 Like, on click the item from the flatlist, it shows the modal with data for selected item.就像,单击 flatlist 中的项目时,它会显示带有所选项目数据的模式。 Here is my code below下面是我的代码

Home.js主页.js

import React, { Component } from 'react';
import { StyleSheet, Text, View, FlatList, Image, TouchableOpacity, Alert, Button } from 'react-native';
import { Popup } from './Modal';
import * as productdata from '../data/productdata.js';

export default class Home extends Component {

    constructor(props) {
        super(props);

        this.state = {
            isLoading: true,
            dataSource: [],
        };
    }

    componentDidMount() {
        this.setState({
            isLoading: false,
            dataSource: productdata.product,
        })
    }

    popupRef = React.createRef()
    onShowPopup = item => {   
       popupRef.show();  
    }
    onClosePopup = () => {
        popupRef.close()
    }


    ProductList = ({ item }) => (
        <View style={styles.listItem}>

            <TouchableOpacity onPress={() => this.onShowPopup(item)} style={{ height: 100, width: 100, justifyContent: "center", alignItems: "center" }}>
                <Image source={item.photo} style={{ width: 100, height: 100, borderRadius: 15 }} />
            </TouchableOpacity>
            <View style={{ alignItems: "center", flex: 1, marginTop: 20 }}>
                <Text style={{ fontWeight: "bold", fontSize: 22 }}>{item.name}</Text>
                <Text style={{ fontSize: 18, fontWeight: "bold" }}>{item.price}</Text>
            </View>
            <Popup name="Product Details" ref={(target) => popupRef = target} onTouchOutside={this.onClosePopup} />

        </View>
    );

    render() {
        return (
            <View style={styles.container}>

                <FlatList
                    data={this.state.dataSource}
                    renderItem={this.ProductList}
                    keyExtractor={item => item.name}
                />
            </View>
        );
    }
}

Modal.js Modal.js

import React, { Component } from 'react';
import { Modal, Dimensions, TouchableWithoutFeedback, StyleSheet, View, Text, Button, Image, TouchableOpacity } from 'react-native';

const deviceHeight = Dimensions.get("window").height
export class Popup extends Component {
    constructor(props) {
        super(props)
        this.state = {
            show: false,   
        }
    }

    show = () => {
        this.setState({ show: true })
    }
    close = () => {
        this.setState({ show: false })
    }

    
    renderOutsideTouchable(onTouch) {
        const view = <View style={{ flex: 1, width: '100%' }} />
        if (!onTouch) return view

        return (
            <TouchableWithoutFeedback onPress={onTouch} style={{ flex: 1, width: '100%' }}>
                {view}
            </TouchableWithoutFeedback>
        )
    }

    renderTitle = () => {
        const { name } = this.props
        return (
            <View style={{ alignItems: 'center' }}>
                <Text style={{
                    color: 'black', fontSize: 20,
                    fontWeight: 'bold', margin: 15
                }}>
                    {name}
                </Text>
            </View>
        )
    }
    renderContent = (item) => {
        return (
            <View style={{ alignItems: 'center', marginBottom: 10 }}>
           <View style={styles.card}>
  <Text style={{ fontSize: 20, fontWeight: '500', fontWeight: 'bold', alignSelf: 'center', margin: 5 }}/>
                   
                    <TouchableOpacity style={styles.buttonContainer}>
                        <Text style={styles.button}>Add to Cart</Text>
                    </TouchableOpacity>
                </View>
            </View>
        )
    }

    render() {
        let { show } = this.state
        const { onTouchOutside, title } = this.props
        return (
         <Modal  animationType={'slide'} transparent={true} visible={show} onRequestClose={this.close}>
          <View style={{ flex: 1, backgroundColor: '#000000AA', justifyContent: 'flex-end' }}>
                    {this.renderOutsideTouchable(onTouchOutside)}
           <View style={{
                        backgroundColor: '#FFFFFF', width: '100%', height: '70%', borderTopRightRadius:20, borderTopLeftRadius: 20, paddingHorizontal: 20, maxHeight: deviceHeight * 5}}>

                        {this.renderTitle()}
                        {this.renderContent()}

                    </View>
                </View>
            </Modal>
        )
    }
}

My Problem: I am not able to pass the flatlist item data to a Modal component and have no better idea solving it in this code.我的问题:我无法将 flatlist 项目数据传递给 Modal 组件,并且没有更好的主意在此代码中解决它。

Please help me and if any including, changes or complete solution for perfect understanding for the requirement would be really great.请帮助我,如果有任何包括、更改或完整的解决方案以完美理解需求,那将非常棒。 Many Thanks in Advance!提前谢谢了!

You don't need to duplicate open state in modal/popup.您不需要在模态/弹出窗口中复制打开状态。 Simply set the style and open.只需设置样式并打开即可。 Assume open close state is controlled by parent component, so if rendering modal/popup it is open by definition.假设打开关闭状态由父组件控制,因此如果渲染模态/弹出窗口,它是根据定义打开的。

class Popup extends React.Component {
  renderOutsideTouchable(onTouch) {
    const view = <View style={{ flex: 1, width: '100%' }} />;
    if (!onTouch) return view;

    return (
      <TouchableWithoutFeedback
        onPress={onTouch}
        style={{ flex: 1, width: '100%' }}>
        {view}
      </TouchableWithoutFeedback>
    );
  }

  renderTitle = () => {
    const { name } = this.props;
    return (
      <View style={{ alignItems: 'center' }}>
        <Text
          style={{
            color: 'black',
            fontSize: 20,
            fontWeight: 'bold',
            margin: 15,
          }}>
          {name}
        </Text>
      </View>
    );
  };

  renderContent = () => {
    const { item } = this.props;
    return (
      <View style={{ alignItems: 'center', marginBottom: 10 }}>
        <View style={styles.card}>
          <Text
            style={{
              fontSize: 20,
              fontWeight: '500',
              // fontWeight: "bold",
              alignSelf: 'center',
              margin: 5,
            }}
          />

          <TouchableOpacity style={styles.buttonContainer}>
            <Text>Name: {item.name}</Text>
            <Text>Price: {item.price}</Text>
            <Text>Description: {item.desc}</Text>
            <Text>Rating: {item.rating}</Text>
            <Text style={styles.button}>Add to Cart</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  };

  render() {
    const { onTouchOutside, title } = this.props;
    return (
      <Modal
        animationType={'slide'}
        transparent
        visible // <-- visible prop is truthy
        onRequestClose={this.close}>
        <View
          style={{
            flex: 1,
            backgroundColor: '#000000AA',
            justifyContent: 'flex-end',
            zIndex: 1000,
          }}>
          {this.renderOutsideTouchable(onTouchOutside)}
          <View
            style={{
              backgroundColor: '#FFFFFF',
              width: '100%',
              height: '70%',
              borderTopRightRadius: 20,
              borderTopLeftRadius: 20,
              paddingHorizontal: 20,
              maxHeight: deviceHeight * 5,
            }}>
            {this.renderTitle()}
            {this.renderContent()}
          </View>
        </View>
      </Modal>
    );
  }
}

A react ref isn't necessary for opening a modal/popup to display a specific item.打开模式/弹出窗口以显示特定项目不需要反应引用。 Change the onShowPopup and onClosePopup to set/nullify a clicked on item.更改onShowPopuponClosePopup以设置/取消单击的项目。 Conditionally render the Popup outside the Flatlist .有条件地在Flatlist之外呈现Popup

class Home extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      dataSource: productdata.product,
      isLoading: false,
      popupItem: null,
    };
  }

  onShowPopup = (popupItem) => {
    this.setState({ popupItem });
  };

  onClosePopup = () => {
    this.setState({ popupItem: null });
  };

  ProductList = ({ item }) => (
    <View style={styles.listItem}>
      <TouchableOpacity
        onPress={() => this.onShowPopup(item)}
        style={{
          height: 100,
          width: 100,
          justifyContent: 'center',
          alignItems: 'center',
        }}>
        <Image
          source={item.photo}
          style={{ width: 100, height: 100, borderRadius: 15 }}
        />
      </TouchableOpacity>
      <View style={{ alignItems: 'center', flex: 1, marginTop: 20 }}>
        <Text style={{ fontWeight: 'bold', fontSize: 22 }}>{item.name}</Text>
        <Text style={{ fontSize: 18, fontWeight: 'bold' }}>{item.price}</Text>
      </View>
    </View>
  );

  render() {
    return (
      <View style={styles.container}>
        {this.state.popupItem && (
          <Popup
            name="Product Details"
            item={this.state.popupItem} // <-- pass pop item
            onTouchOutside={this.onClosePopup}
          />
        )}
        <FlatList
          data={this.state.dataSource}
          renderItem={this.ProductList}
          keyExtractor={(item) => item.name}
        />
      </View>
    );
  }
}

Expo Snack世博小吃

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

相关问题 如何在 React Native 的类组件中将函数作为道具传递和执行? - How to pass and execute functions as props in class Component in React Native? 如何在 Input 组件的 inputContainerStyle 中将 backgroundColor 作为道具传递给本机元素 - How to pass backgroundColor as props in inputContainerStyle in Input component react native elements 如何解构道具以传递给子组件? REACT-NATIVE - How to destructure props to pass for childs component? REACT-NATIVE 将道具传递给子组件 - React Native - Pass props to child component - React Native 无法将 Props 传递给 React Native 中的另一个组件 - Cannot Pass Props to another component in React Native 如何将 React 组件作为道具传递给另一个组件 - How to pass React Component as props to another component React Native:如何在 React Navigation 中传递 props - React Native: How to pass props in React Navigation 将道具从模式传递到其他组件反应导航 - Pass props from Modal to other Component react navigation 如何使用 React Native 中的 props 将数组从父组件传递到子组件? - How to pass an array from a parent component to child component using props in React Native? 如何将 react-native 道具从功能组件传递到 class 组件 - How to pass react-native props from functional component to class component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM