react-native如何在另一个中使用组件的变量

How to use the Variable of Component in another in react-native

您好,亲爱的,感谢您上门帮助我,我有一个名为 PlayerWidget 的组件,我想使用它状态变量是 isPlaying 相册中的值Header 组件

这是我的代码

PlayerWidget

import React, { useContext, useEffect, useState } from 'react';
import { Text, Image, View, TouchableOpacity } from 'react-native';
import { AntDesign, FontAwesome } from "@expo/vector-icons";
import { API, graphqlOperation } from 'aws-amplify';

import styles from './styles';
import { Song } from "../../types";
import { Sound } from "expo-av/build/Audio/Sound";

import { AppContext, Status } from '../../AppContext';
import { getSong } from "../../src/graphql/queries";

const PlayerWidget = () => {

    const [song, setSong] = useState(null);
    const [sound, setSound] = useState<Sound | null>(null);
    //this is the Variable I will like to use in my AlbumHeader Component isPlaying
    const [isPlaying, setIsPlaying] = useState<boolean>(true);

    const [duration, setDuration] = useState<number | null>(null);
    const [position, setPosition] = useState<number | null>(null);

    //const { songStatus, setSongStatus } = useContext(Status);

    setSongStatus(isPlaying);
    

    const { songId } = useContext(AppContext);



    useEffect(() => {
        const fetchSong = async () => {
            try {
                const data = await API.graphql(graphqlOperation(getSong, { id: songId }))

                setSong(data.data.getSong);
            } catch (e) {
                console.log(e);
            }
        }

        fetchSong();
    }, [songId])

    const onPlaybackStatusUpdate = (status) => {
        setIsPlaying(status.isPlaying);
        setDuration(status.durationMillis);
        setPosition(status.positionMillis);


    }

    const playCurrentSong = async () => {

        if (song.artist.length > 10) {
            song.artist = song.artist.substring(0, 6) + "...";
        }

        if (song.title.length > 8) {
            song.title = song.title.substring(0, 5) + "...";
        }
        if (sound) {
            await sound.unloadAsync();
        }

        const { sound: newSound } = await Sound.createAsync(
            { uri: song.uri },
            { shouldPlay: isPlaying },
            onPlaybackStatusUpdate
        )

        setSound(newSound)
    }

    useEffect(() => {
        if (song) {
            playCurrentSong();
        }
    }, [song])

    const onPlayPausePress = async () => {
        if (!sound) {
            return;
        }
        if (isPlaying) {
            await sound.stopAsync();
        } else {
            await sound.playAsync();
        }
    }

    const getProgress = () => {
        if (sound === null || duration === null || position === null) {
            return 0;
        }

        return (position / duration) * 100;
    }

    if (!song) {
        return null;
    }

    return (
        <View style={styles.container}>
            <View style={[styles.progress, { width: `${getProgress()}%` }]} />
            <View style={styles.row}>
                <Image source={{ uri: song.imageUri }} style={styles.image} />
                <View style={styles.rightContainer}>
                    <View style={styles.nameContainer}>
                        <Text style={styles.title}>{song.title}</Text>
                        <Text style={styles.artist}>{song.artist}</Text>
                    </View>

                    <View style={styles.iconsContainer}>
                        <AntDesign name="hearto" size={20} color={'white'} />
                        <TouchableOpacity onPress={onPlayPausePress}>
                            <AntDesign name={isPlaying ? 'pausecircleo' : 'playcircleo'} size={25} color={'white'} />
                        </TouchableOpacity>

                    </View>

                </View>

            </View>

        </View>
    )
}


export default PlayerWidget;

这是另一个(Album Header)组件,我想在

中使用isPlaying值
import React from 'react';
import { useContext } from 'react';
import { View, Text, Image } from 'react-native';
import { TouchableOpacity } from 'react-native-gesture-handler';
import { AppContext, Status } from '../../AppContext';
import { Album } from '../../types';
import styles from './styles';


export type AlbumHeaderProp = {
    album: Album;
}

const AlbumHeader = (props: AlbumHeaderProp) => {

    const { album } = props;

    const { setSongId, songId } = useContext(AppContext);
    var playalbumSong = new Array();

    const { songStatus } = useContext(Status);

    const playallSong = () => {
        const name = 'name';

        console.log("I will play all the songs George huum");
        const myArray = album.songs.items;

        myArray.forEach((element: any, index: number, array: any) => {
            playalbumSong.push(element.id);
          

        });


        console.log(songStatus);
        setSongId(playalbumSong[0]);

    }
    return (
        <View style={styles.container}>
            <Image source={{ uri: album.imageUri }} style={styles.image} />
            <Text style={styles.name}>{album.name}</Text>

            <View style={styles.creatorContainer}>
                <Text style={styles.creator}>By {album.by}</Text>
                <Text style={styles.likes}>{album.numberOfLikes} Likes</Text>
            </View>
            <TouchableOpacity onPress={playallSong}>
                <View style={styles.button}>
                    <Text style={styles.buttonText}>Play</Text>
                </View>
            </TouchableOpacity>

        </View>
    )
}

export default AlbumHeader;

如果 AlbumHeader 不是 PlayerWidget 的子项,您也需要使用全局状态,f.e。 react-redux 或 reducer 钩子。

我通过相同类型的上下文传递该变量的值来解决这个问题,如果您使用反应钩子和功能组件,此方法有效