如何在React中动态生成导入文件的路径

时间:2019-11-14 09:07:55

标签: javascript reactjs typescript

我在生成动态路径以在React中导入文件时遇到问题。 我使用map()函数来生成代码的动态部分,该部分是由几个相同的div元素组成的序列,并且该div中包含一个音频元素。这段代码如下:

    {soundsName.map((sound, i) => {
          return (
            <div
              className="drum-pad"
              onClick={this.soundPlay}
              title={"Sound " + sound}
              key={i}
            >
              <audio className="clip" id={sound}>
                <source src={`s${i}`} type="audio/mpeg"></source>
              </audio>
              {sound}
            </div>
          );
        })}

我的问题是,在'src'中为'source'元素生成的路径是错误的。 该路径仅是导入文件的名称,例如“ s1”,“ s2”,“ s3”等。

文件是这样导入的:

    import s0 from "./assets/sounds/s1.mp3";
    import s1 from "./assets/sounds/s2.mp3";
    import s2 from "./assets/sounds/s3.mp3";
    import s3 from "./assets/sounds/s4.mp3";
    import s4 from "./assets/sounds/s5.mp3";
    import s5 from "./assets/sounds/s6.mp3";
    import s6 from "./assets/sounds/s7.mp3";
    import s7 from "./assets/sounds/s8.mp3";
    import s8 from "./assets/sounds/s9.mp3";

我真的不知道,我在做什么错了:( 也许有些人知道吗?

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

您应将源代码设为SourceBuffer,而不是./assets/sounds/s${i}.mp3,您将获得以下s${i}

针对您的具体情况进行修改:

将所有组件放入一个数组中,例如:

src="./assets/sounds/s1.mp3"

然后在您的let soundPaths = [s1, s2, s3, s4 /*... and rest of components */] 函数中执行

map()

答案 1 :(得分:0)

import s0 from "./assets/sounds/s1.mp3";
import s1 from "./assets/sounds/s2.mp3";
import s2 from "./assets/sounds/s3.mp3";
import s3 from "./assets/sounds/s4.mp3";
import s4 from "./assets/sounds/s5.mp3";
import s5 from "./assets/sounds/s6.mp3";
import s6 from "./assets/sounds/s7.mp3";
import s7 from "./assets/sounds/s8.mp3";
import s8 from "./assets/sounds/s9.mp3";

sound=[
    {
       sound_name:"s1"
       path:s1
    },
    {
       sound_name:"s2"
       path:s2
    },    {
       sound_name:"s3"
       path:s3
    },    {
       sound_name:"s4"
       path:s4
    },    {
       sound_name:"s5"
       path:s5
    },    {
       sound_name:"s6"
       path:s6
    },    {
       sound_name:"s7"
       path:s7
    },    {
       sound_name:"s8"
       path:s8
    },
]

这是一种方式


   {soundsName.map((sound, i) => {
          return (
            <div
              className="drum-pad"
              onClick={this.soundPlay}
              title={"Sound " + sound.sound_name}
              key={i}
            >
              <audio className="clip" id={sound.sound_name}>
                <source src=sound.path type="audio/mpeg"></source>
              </audio>
              {sound.sound_name}
            </div>
          );
        })}