我可以在 Javascript/React 的 ```require()``` 括号中使用对象吗?

问题描述 投票:0回答:0

我有一个非常简单的应用程序,它有一个按钮。 当您按下按钮时,应用程序会播放声音。 当我设置声音文件的路径时,我使用

require(`./assets/${array[0].bgm}.mp3`)
。 但是,我得到一个错误。

我怎样才能让它发挥作用?

这是一个数组,我将在其中获取路径的名称

bgm

数组.js

const array = [
  {
    id: 1,
    name: "Ken",
    bgm: "bgm",
  },
];

export default array;

这是 app.js.

import * as React from "react";
import { Text, View, StyleSheet, Button } from "react-native";
import { Audio } from "expo-av";
import SoundPlayer from "./SoundPlayer";

export default function App() {
  return (
    <View style={styles.container}>
      <SoundPlayer />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    backgroundColor: "#ecf0f1",
    padding: 10,
  },
});

这是另一个包含

require()

的文件
import * as React from "react";
import { Button } from "react-native";
import { Audio } from "expo-av";

import array from "./array";

export default function SoundPlayer() {
  const [sound, setSound] = React.useState();

  async function playSound() {
    console.log("Loading Sound");
    if (sound) {
      console.log("Unloading Sound");
      await sound.unloadAsync();
    }
    const { sound: newSound } = await Audio.Sound.createAsync(
      require(`./assets/${array[0].bgm}.mp3`) // This doesn't work.

      //require("./assets/bgm.mp3") //This just works.
     
    );
    setSound(newSound);

    console.log("Playing Sound");
    await newSound.playAsync();
  }

  React.useEffect(() => {
    return sound
      ? () => {
          console.log("Unloading Sound");
          sound.unloadAsync();
        }
      : undefined;
  }, [sound]);

  return <Button title="Play Sound" onPress={playSound} />;
}

但是,这会引发错误:

error: SoundPlayer.js: SoundPlayer.js:Invalid call at line 17: require("./assets/" + _array.default[0].bgm + ".mp3")

我需要一些帮助。 你会如何解决这个问题? 提前谢谢你。

javascript reactjs require
© www.soinside.com 2019 - 2024. All rights reserved.