FlatList nie widać ikon

0

Chce stworzyć menu z kafelek ale mam problem z wyświetleniem grafiki. Pojawia mi się tekst title ale grafika już nie

const link = require('../assets/logo.png');

const product = [
  {
    title: 'pierwszy',
    image: 'link'
  },
  {
    title: 'drugi',
    image: 'link'
  },
  {
    title: 'trzeci',
    image: 'link'
  },
  {
    title: 'cztery',
    image: 'link'
  }
];

function ServiceHandler() {
  () => navigation.navigate('Service')
}

function ServiceScreen() {

  const navigation = useNavigation();

  return (
    <BackgroundImage>
      <CustomHeader backButton={() => navigation.navigate('Home')} />
      <View style={styles.rootContainer}>
        <SafeAreaView >
        <FlatList 
          numColumns={3}
          data={product}
          keyExtractor={(item, index) => index.toString()}
          renderItem={({ item }) => (<Product product={item} />)}></FlatList>
          </SafeAreaView>
      </View>
    </BackgroundImage>
  );
}

I moja klasa produkty

import React from "react";
import { View, Text, Image} from "react-native";

class Product extends React.Component {
    render(){
        const {title, image} = this.props.product
        return (
            <View style={{width:'48%', alignItems: 'center', borderWidth: 0.75, marginHorizontal:'1%', borderColor: 'white'}}>
                <Text>{title}</Text>
                <Image source={{image}}/>
            </View>
        )
    }
}

export default Product;
1
TakMaszRacje napisał(a):
const link = require('../assets/logo.png');

const product = [
  {
    title: 'pierwszy',
    image: 'link'
  },
  {
    title: 'drugi',
    image: 'link'
  },
  {
    title: 'trzeci',
    image: 'link'
  },
  {
    title: 'cztery',
    image: 'link'
  }
];

Źle przekazujesz zmienną link do obiektu.

Spróbuj w taki sposób

const link = require('../assets/logo.png');

const product = [
  {
    title: "Lorem ipsum",
    image: link
  }
];
1

a możesz mi jeszcze podpowiedzieć jak zrobić aby można było zrobić ikonki aktywne. Chce żeby po naciśnięciu danej ikonki dodawał mi się do list ten produkt np po id. Dorobię id do tego jeszcze

Mogę zrobić przykład w zwykłym Reactcie, a ty sobie to przerobisz na Native.

import React, { useState } from "react";
import ReactDOM from "react-dom";

// Zamieniłem tablicę na obiekt, żeby uprościć dodawanie i usuwanie elementów z listy
const products = {
  1: { // <-- klucz musi być zawsze równy id
    id: 1,
    title: "Lorem ipsum 1",
    image: "...",
    imageAlt: "..."
  },
  2: {
    id: 2,
    title: "Lorem ipsum 2",
    image: "...",
    imageAlt: "..."
  },
  3: {
    id: 3,
    title: "Lorem ipsum 3",
    image: "...",
    imageAlt: "..."
  },
  //...
  1023: {
    id: 1023,
    title: "Lorem ipsum 1023",
    image: "...",
    imageAlt: "..."
  }
};

// Do komponentu Product przekazujemy funkcję toggleProduct, która odpowiada za dodanie lub usunięcie produktu z listy
const Product = ({ toggleProduct, ...product }) => (
  <div style={{ marginTop: "15px" }}>
    {product.title}
    <img src={product.image} alt={product.imageAlt} />
    {toggleProduct && (
      <button onClick={() => toggleProduct(product.id, product)}>
        Zmień status
      </button>
    )}
  </div>
);

const App = () => {
  // Tworzymy stan
  const [activeProducts, setActiveProducts] = useState({});

  // Tworzymy funkcję odpowiedzialną za dodawanie i usuwanie produktu
  const toggleProduct = (id, product) => {
    if (activeProducts[id]) {
      setActiveProducts((prevProducts) => {
        delete prevProducts[id];

        // Jeśli aktualizujemy stan, który jest tablicą, lub obiektem to musimy zwrócić całkowicie nową wartość
        return { ...prevProducts }; 
      });
    } else {
      setActiveProducts({
        ...activeProducts,
        [id]: product
      });
    }
  };

  return (
    <>
      Lista wszystkich produktów:
      {/* Teraz cała lista jest w formie obiektu, więc przy wyświetlaniu musimy z powrotem przekształcić ją w tablice */}
      {Object.values(products).map((props) => (
        <Product key={props.id} {...props} toggleProduct={toggleProduct} />
      ))}
      <br />
      <br />
      Lista aktywnych produktów:
      {Object.values(activeProducts).map((props) => (
        <Product key={props.id} {...props} />
      ))}
    </>
  );
};

ReactDOM.render(<App />, document.getElementById("container"));

Cała zasada polega na tym, że w jednym komponencie musisz stworzyć stan, oraz funkcję do zmiany tego stanu i przekazać je do komponentów potomnych takich jak mój Product,

0

A mazes mi jeszcze pwiedzieć dlaczego dostaje byład?

class Product extends React.Component {

    const navigation = useNavigation();

    render() {
        const { id, image, title, } = this.props.product
        
        return (

            <View style={styles.rootCointener}>
                <TouchableOpacity onPress={() =>  {navigation.replace('Service')}}>
                    <Image style={styles.imageCointener} source={image} />
                </TouchableOpacity>
                <Text style={styles.textCointener}>{title}</Text>
            </View>
        )
    }
}

TransformError SyntaxError: test/Product.js: Unexpected token (12:10)

10 | class Product extends React.Component {
11 |

12 | const navigation = useNavigation();
| ^
13 |
14 | render() {
15 | const { id, image, title, } = this.props.product
at http://192.168.18.129:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&strict=false&minify=false:35674:25 in showCompileError
at http://192.168.18.129:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&strict=false&minify=false:35593:28 in <unknown>
at http://192.168.18.129:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&strict=false&minify=false:36109

0

@TakMaszRacje, ponieważ hooki działają jedynie w komponentach funkcyjnych, a to jest klasowy.

0

Zminiłem ale w tej chwilo lista mi się nie pojawiła

function  Product(id, image, title) {

    const navigation = useNavigation();
 
        return (

            <View style={styles.rootCointener}>
                <TouchableOpacity onPress={() =>  {navigation.replace('Service')}}>
                    <Image style={styles.imageCointener} source={image} />
                </TouchableOpacity>
                <Text style={styles.textCointener}>{title}</Text>
            </View>

1 użytkowników online, w tym zalogowanych: 0, gości: 1