簡體   English   中英

如何傳遞數據項以反應本機模式

[英]How to pass data item to react native modal

我試圖通過點擊按鈕“查看模式”將數據項傳遞給反應原生模態,但似乎我在代碼中遺漏了一些東西。

這是循環顯示在時間軸屏幕上的數據對象

Object {
  "farmer_id": "4",
  "farmer_name": "Joshua Adebisi",
  "id": "4",
  "product_description": "The grains of rice is good for healthy.It is durable,I
t is Awesome Intesrest buyers can contact via contact 08073047104.",
  "product_image": "https://via.placeholder.com/600/cb47e2",
  "product_name": "5kg Grains of Rice",
  "profile_img": "https://via.placeholder.com/150/cb47e2",
  "uploaded_time": "2019-06-10 23:48:04",
}
Object {
  "farmer_id": "3",
  "farmer_name": "Omolewa Stephen",
  "id": "3",
  "product_description": "The grains of rice is good for healthy.It is durable,I
t is Awesome Intesrest buyers can contact via contact 08073047104.",
  "product_image": "https://via.placeholder.com/600/4dcdf6",
  "product_name": "5kg Grains of Rice",
  "profile_img": "https://via.placeholder.com/150/cb47e2",
  "uploaded_time": "2019-06-10 23:48:04",
}
Object {
  "farmer_id": "2",
  "farmer_name": "Salami Paul",
  "id": "2",
  "product_description": "The grains of rice is good for healthy.It is durable,I
t is Awesome Intesrest buyers can contact via contact 08073047104.",
  "product_image": "https://via.placeholder.com/600/cb47e2",
  "product_name": "5kg Grains of Rice",
  "profile_img": "https://via.placeholder.com/150/cb47e2",
  "uploaded_time": "2019-06-10 23:48:04",
}
Object {
  "farmer_id": "1",
  "farmer_name": "Adebiyi Samuel",
  "id": "1",
  "product_description": "The grains of rice is good for healthy.It is durable,T
he grains of rice is good for healthy.It is durable.It is Awesome Intesrest buye
rs can contact via contact 08073047104.

",
  "product_image": "https://via.placeholder.com/600/4dcdf6",
  "product_name": "5kg Grains of Beans",
  "profile_img": "https://via.placeholder.com/150/cb47e2",
  "uploaded_time": "2019-06-11 02:56:53",
}

這是時間線代碼

import React, {Component} from 'react';
import {TextInput,Modal,Alert,TouchableHighlight,StyleSheet,RefreshControl ,ScrollView,Dimensions,Image,StatusBar,ActivityIndicator,Text, View,TouchableOpacity,KeyboardAvoidingView} from 'react-native';
import { createBottomTabNavigator,createStackNavigator,createSwitchNavigator, createAppContainer} from "react-navigation";
let {height, width} = Dimensions.get('window');
import { Ionicons } from '@expo/vector-icons';
import { Font } from 'expo';
import { AsyncStorage } from 'react-native';
export default class Timeline extends Component {
  constructor(props){
    super(props)
    console.log(props)
    this.state = {
      username: '',
      photo: '',
      email: '',
      userId: '',
      address: '',
      timeline: [],
      modalVisible: false,
      refreshing: false
    }
  }
 setModalVisible(visible) {
   this.setState({modalVisible: visible});
 }
  Home = () => {
    alert("Home");
  }
  PostTimeline = () => {
    return fetch( "http://texotrack.com/api/user/timeline.php", {
      method: "POST",
      headers:{
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        action: 'fetch'
      })
    }).then((response) => response.json()).then((responseJsonFromServer) => {
        this.setState({
          timeline: responseJsonFromServer
        });
    })
  }

componentDidMount(){
    this.PostTimeline();
    AsyncStorage.getItem("key").then((data) =>{
      const val = JSON.parse(data);
      this.setState({
        username: data.name,
        photo: data.photo,
        email: data.email,
        userId: data.id,
        address: data.address
      })
    })
  }

  render() {
        const timeLineList = this.state.timeline.map((data) => {
          console.log(data);
        const thumbnail = data.profile_img;
        const product_image = data.product_image;
        return (
          <View elevation={5} key={data.id} style={styles.card}>
          <Modal
              animationType="fade"
              transparent={false}
              visible={this.state.modalVisible}
              key={data.id}
              onRequestClose={() => {
                  alert('Modal has been closed.');
               }}>
              <View style={{margin: 10}}>
                <Text style={styles.headerText}>Product details: {data.product_name}</Text>
                <View style={styles.cardheader}>
                  <View style={styles.miniheader}>
                    <Image style={styles.thumbnail} source={{uri: thumbnail}} />
                    <Text style={styles.thumb_name}>{data.farmer_name}</Text>
                  </View>
                  <Text style={styles.timestamp}>{data.uploaded_time}</Text>
                </View>
                <View style={styles.cardbody}>
                  <Image style={styles.cardbody_image} source={{uri: product_image}}/>
                   <Text style={styles.p_name}>{data.product_name}</Text>
                   <Text style={styles.p_desc}>{data.product_description}</Text>
                 <View>
                 </View>
                 </View>

                  <TouchableHighlight
                    onPress={() => {
                      this.setModalVisible(!this.state.modalVisible);
                    }}>
                    <Text>Close</Text>
                  </TouchableHighlight>
                </View>

           </Modal>
            <View style={styles.cardheader}>
              <View style={styles.miniheader}>
                <Image style={styles.thumbnail} source={{uri: thumbnail}} />
                <Text style={styles.thumb_name}>{data.farmer_name}</Text>
              </View>
              <Text style={styles.timestamp}>{data.uploaded_time}</Text>
            </View>
            <View style={styles.cardbody}>
              <Image style={styles.cardbody_image} source={{uri: product_image}}/>
             <Text style={styles.p_name}>{data.product_name}</Text>
             <Text style={styles.p_desc}>{data.product_description}</Text>
             <View>
             <TouchableOpacity
                onPress={() => {
                  this.setModalVisible(true);
                }} style={styles.buttonContainer}>
                <Text style={styles.buttonText}>Show Modal</Text>
              </TouchableOpacity>
             </View>
            </View>
          </View>
        )
      });

      return (
        <View style={styles.container}>
            <View elevation={5} style={styles.mainheader}>
               <Text style={styles.iconTop} onPress={() => this.PostTimeline()}>
                  <Ionicons name="md-refresh" size={32} color="black" />
               </Text>
               <Text style={styles.headerTitle}>Home</Text>
               <Text style={styles.iconTop} onPress={() => this.Home()}>
                  <Ionicons name="md-home" size={32} color="black" />
               </Text>
            </View>

            <View style={styles.content}>
               <View style={{padding: 10}}>
                 <Text style={styles.headerText}><Ionicons name="md-cart"  size={26} color="black" /> Marketplace</Text>
               </View>
               <View style={{flex:1}}>
                 <ScrollView alwaysBounceVertical={true} contentContainerStyle={{ flexGrow: 1}} enabled bounces={true}>
                  {timeLineList}
                 </ScrollView>
               </View>
            </View>
        </View>
      );
    }

  }

重點是這里使用模態的渲染方法,如何在單擊每個按鈕查看詳細信息時將數據項傳遞給模態。 謝謝

  render() {
        const timeLineList = this.state.timeline.map((data) => {
          console.log(data);
        const thumbnail = data.profile_img;
        const product_image = data.product_image;
        return (
          <View elevation={5} key={data.id} style={styles.card}>
          <Modal
              animationType="fade"
              transparent={false}
              visible={this.state.modalVisible}
              key={data.id}
              onRequestClose={() => {
                  alert('Modal has been closed.');
               }}>
              <View style={{margin: 10}}>
                <Text style={styles.headerText}>Product details: {data.product_name}</Text>
                <View style={styles.cardheader}>
                  <View style={styles.miniheader}>
                    <Image style={styles.thumbnail} source={{uri: thumbnail}} />
                    <Text style={styles.thumb_name}>{data.farmer_name}</Text>
                  </View>
                  <Text style={styles.timestamp}>{data.uploaded_time}</Text>
                </View>
                <View style={styles.cardbody}>
                  <Image style={styles.cardbody_image} source={{uri: product_image}}/>
                   <Text style={styles.p_name}>{data.product_name}</Text>
                   <Text style={styles.p_desc}>{data.product_description}</Text>
                 <View>
                 </View>
                 </View>

                  <TouchableHighlight
                    onPress={() => {
                      this.setModalVisible(!this.state.modalVisible);
                    }}>
                    <Text>Close</Text>
                  </TouchableHighlight>
                </View>

           </Modal>
            <View style={styles.cardheader}>
              <View style={styles.miniheader}>
                <Image style={styles.thumbnail} source={{uri: thumbnail}} />
                <Text style={styles.thumb_name}>{data.farmer_name}</Text>
              </View>
              <Text style={styles.timestamp}>{data.uploaded_time}</Text>
            </View>
            <View style={styles.cardbody}>
              <Image style={styles.cardbody_image} source={{uri: product_image}}/>
             <Text style={styles.p_name}>{data.product_name}</Text>
             <Text style={styles.p_desc}>{data.product_description}</Text>
             <View>
             <TouchableOpacity
                onPress={() => {
                  this.setModalVisible(true);
                }} style={styles.buttonContainer}>
                <Text style={styles.buttonText}>Show Modal</Text>
              </TouchableOpacity>
             </View>
            </View>
          </View>
        )
      });

      return (
        <View style={styles.container}>
            <View elevation={5} style={styles.mainheader}>
               <Text style={styles.iconTop} onPress={() => this.PostTimeline()}>
                  <Ionicons name="md-refresh" size={32} color="black" />
               </Text>
               <Text style={styles.headerTitle}>Home</Text>
               <Text style={styles.iconTop} onPress={() => this.Home()}>
                  <Ionicons name="md-home" size={32} color="black" />
               </Text>
            </View>

            <View style={styles.content}>
               <View style={{padding: 10}}>
                 <Text style={styles.headerText}><Ionicons name="md-cart"  size={26} color="black" /> Marketplace</Text>
               </View>
               <View style={{flex:1}}>
                 <ScrollView alwaysBounceVertical={true} contentContainerStyle={{ flexGrow: 1}} enabled bounces={true}>
                  {timeLineList}
                 </ScrollView>
               </View>
            </View>
        </View>
      );
    }

如果有更好的方法來重構此代碼,我願意學習。 謝謝

我已經很快改變了你的代碼,讓你知道如何在下面檢查這個應該工作。

無需循環模態將數據設置為按下按鈕時的狀態,模態可以從狀態讀取數據。

 import React, {Component} from 'react';
import {TextInput,Modal,Alert,TouchableHighlight,StyleSheet,RefreshControl ,ScrollView,Dimensions,Image,StatusBar,ActivityIndicator,Text, View,TouchableOpacity,KeyboardAvoidingView} from 'react-native';
import { createBottomTabNavigator,createStackNavigator,createSwitchNavigator, createAppContainer} from "react-navigation";
let {height, width} = Dimensions.get('window');
import { Ionicons } from '@expo/vector-icons';
import { AsyncStorage } from 'react-native';
export default class Timeline extends Component {
  constructor(props){
    super(props)
    console.log(props)
    this.state = {
      username: '',
      photo: '',
      email: '',
      userId: '',
      address: '',
      timeline: [],
      modalVisible: false,
      refreshing: false,
      selectedData: [],
    }
  }
 setModalVisible(visible) {
   this.setState({modalVisible: visible});
 }
  Home = () => {
    alert("Home");
  }
  PostTimeline = () => {
    return fetch( "http://texotrack.com/api/user/timeline.php", {
      method: "POST",
      headers:{
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        action: 'fetch'
      })
    }).then((response) => response.json()).then((responseJsonFromServer) => {
        this.setState({
          timeline: responseJsonFromServer
        });
    })
  }

componentDidMount(){
    this.PostTimeline();
    AsyncStorage.getItem("key").then((data) =>{
      const val = JSON.parse(data);
      this.setState({
        username: data.name,
        photo: data.photo,
        email: data.email,
        userId: data.id,
        address: data.address
      })
    })
  }

  _selectedItem = (data) => {
    this.setState({selectedData: data});
    this.setModalVisible(true);
  }

  render() {
        const data = this.state.selectedData
        const timeLineList = this.state.timeline.map((data) => {
          console.log(data);
        const thumbnail = data.profile_img;
        const product_image = data.product_image;
        return (
          <View elevation={5} key={data.id} style={styles.card}>
            <View style={styles.cardheader}>
              <View style={styles.miniheader}>
                <Image style={styles.thumbnail} source={{uri: thumbnail}} />
                <Text style={styles.thumb_name}>{data.farmer_name}</Text>
              </View>
              <Text style={styles.timestamp}>{data.uploaded_time}</Text>
            </View>
            <View style={styles.cardbody}>
              <Image style={styles.cardbody_image} source={{uri: product_image}}/>
             <Text style={styles.p_name}>{data.product_name}</Text>
             <Text style={styles.p_desc}>{data.product_description}</Text>
             <View>
             <TouchableOpacity
                onPress={() => {
                  this._selectedItem(data);
                }} style={styles.buttonContainer}>
                <Text style={styles.buttonText}>Show Modal</Text>
              </TouchableOpacity>
             </View>
            </View>
          </View>
        )
      });

      return (
        <View style={styles.container}>
            <View elevation={5} style={styles.mainheader}>
               <Text style={styles.iconTop} onPress={() => this.PostTimeline()}>
                  <Ionicons name="md-refresh" size={32} color="black" />
               </Text>
               <Text style={styles.headerTitle}>Home</Text>
               <Text style={styles.iconTop} onPress={() => this.Home()}>
                  <Ionicons name="md-home" size={32} color="black" />
               </Text>
            </View>

            <View style={styles.content}>
               <View style={{padding: 10}}>
                 <Text style={styles.headerText}><Ionicons name="md-cart" size={26} color="black" /> Marketplace</Text>
               </View>
               <View style={{flex:1}}>
                 <ScrollView alwaysBounceVertical={true} contentContainerStyle={{ flexGrow: 1}} enabled bounces={true}>
                  {timeLineList}
                 </ScrollView>
               </View>
            </View>

            <Modal
                animationType="fade"
                transparent={false}
                visible={this.state.modalVisible}
                key={data.id}
                onRequestClose={() => {
                    alert('Modal has been closed.');
                }}>
                <View style={{margin: 10}}>
                <Text style={styles.headerText}>Product details: {data.product_name}</Text>
                <View style={styles.cardheader}>
                    <View style={styles.miniheader}>
                    <Image style={styles.thumbnail} source={{uri: data.thumbnail}} />
                    <Text style={styles.thumb_name}>{data.farmer_name}</Text>
                    </View>
                    <Text style={styles.timestamp}>{data.uploaded_time}</Text>
                </View>
                <View style={styles.cardbody}>
                    <Image style={styles.cardbody_image} source={{uri: data.product_image}}/>
                    <Text style={styles.p_name}>{data.product_name}</Text>
                    <Text style={styles.p_desc}>{data.product_description}</Text>
                <View>
                </View>
                </View>

                    <TouchableHighlight
                    onPress={() => {
                        this.setModalVisible(!this.state.modalVisible);
                    }}>
                    <Text>Close</Text>
                    </TouchableHighlight>
                </View>
            </Modal>

        </View>
      );
    }

  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM