gpt4 book ai didi

reactjs - 如何对多个元素使用一个 useRef?或者如何将 useRef 用于类似的行为?

转载 作者:行者123 更新时间:2023-12-02 00:09:48 27 4
gpt4 key购买 nike

我有多个按钮,单击它们会触发不同的音频文件。

我设法为每个按钮使用不同的 useRef 使其工作,但我想有更好的方法来实现这一点:

const App = () => {

const myAudio1 = useRef()
const myAudio2 = useRef()
const myAudio3 = useRef()

const handleAudio1 = () => {
myAudio1.current.play()
}

const handleAudio2 = () => {
myAudio2.current.play()
}

const handleAudio3 = () => {
myAudio3.current.play()
}

return (
<div id="drum-machine">
<div onClick={() => handleAudio1()} id="Btn1">
<div> Button 1
<audio ref={myAudio1}>
<source id="Btn1" src="drumSounds/sound1.wav" type="audio/mpeg"/>
</audio>
</div>
</div>

<div onClick={() => handleAudio2()} id="Btn2">
<div> Button 2
<audio ref={myAudio2}>
<source id="Btn2" src="drumSounds/sound2.wav" type="audio/mpeg"/>
</audio>
</div>
</div>

<div onClick={() => handleAudio3()} id="Btn3">
<div> Button 3
<audio ref={myAudio3}>
<source id="Btn3" src="drumSounds/sound3.wav" type="audio/mpeg"/>
</audio>
</div>
</div>
</div>
)
}

最佳答案

您不能在循环中使用 React Hooks,但您可以将使用 useRef 的代码封装到它自己的组件中,然后为每个音频源渲染该组件。例如:

const AudioSource = ({ children, src, encoding = "audio/mpeg" }) => {
const ref = React.useRef();
const onClick = React.useCallback(() => {
if (ref.current === undefined) {
return;
}

ref.current.play();
}, []);

return (
<div onClick={onClick}>
{children}
<audio ref={ref}>
<source src={src} type={encoding} />
</audio>
</div>
);
};

然后可以这样调用:

const App = () => {
const sources = [
{
id: "Btn1",
text: "Button 1",
source: "drumSounds/sound1.wav"
},
{
id: "Btn2",
text: "Button 2",
source: "drumSounds/sound2.wav"
},
{
id: "Btn3",
text: "Button 3",
source: "drumSounds/sound3.wav"
}
];

return (
<div id="drum-machine">
{sources.map(audioSource => (
<div key={audioSource.id} id={audioSource.id}>
<AudioSource src={audioSource.src}>{audioSource.text}</AudioSource>
</div>
))}
</div>
);
};

关于reactjs - 如何对多个元素使用一个 useRef?或者如何将 useRef 用于类似的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59448579/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com