如何在反应按钮的 if then 语句上放置图标
How to place an icon on an if then statement for a react button
我正在尝试创建一个按钮,单击该按钮时将显示不同的图标和消息。但是,我不确定如何在 < button >
元素中的 'if then' 语句中包含图标。我对 React 很陌生。
我的代码如下:
import React, { setState, useState, useEffect } from "react";
import { Pause,
Play } from 'react-feather';
function AudioPlayer() {
// use Audio constructor to create HTMLAudioElement
const audioTune = new Audio("<YOUR_AUDIO_FILE_PATH.mp3>");
// variable to play audio in loop
const [playInLoop, setPlayInLoop] = useState(false);
// variable to play audio in loop
const [isPlay, isPlaying] = useState(0);
// load audio file on component load
useEffect(() => {
audioTune.load();
}, []);
// play audio sound
const playSound = () => {
audioTune.play();
isPlaying(1);
};
// pause audio sound
const pauseSound = () => {
audioTune.pause();
};
// stop audio sound
const stopSound = () => {
audioTune.pause();
audioTune.currentTime = 0;
isPlaying(0);
};
const handlePlaying = () => {
if (isPlay) {
stopSound();
} else {
playSound();
}
};
return (
<div>
<div className="App">
<button onClick={handlePlaying}>
{isPlay ? <Pause /> "pause" : <Play/> "listen to this page"}
</button>
</div>
</div>
);
}
export default AudioPlayer;
这里出现错误 {isPlay ? <Pause /> "pause" : <Play/> "listen to this page"}
错误是:
SyntaxError
/src/components/Audio2.js: Unexpected token, expected ":" (57:30)
我尝试在“”标记内插入图标,但这只是将按钮代码显示为字符串。
感谢您的帮助
你可以这样做
<button onClick={handlePlaying}>
{isPlay ? (
<>
<Pause /> Pause
</>
) : (
<>
<Play /> Listen to this page
</>
)}
</button>;
我正在尝试创建一个按钮,单击该按钮时将显示不同的图标和消息。但是,我不确定如何在 < button >
元素中的 'if then' 语句中包含图标。我对 React 很陌生。
我的代码如下:
import React, { setState, useState, useEffect } from "react";
import { Pause,
Play } from 'react-feather';
function AudioPlayer() {
// use Audio constructor to create HTMLAudioElement
const audioTune = new Audio("<YOUR_AUDIO_FILE_PATH.mp3>");
// variable to play audio in loop
const [playInLoop, setPlayInLoop] = useState(false);
// variable to play audio in loop
const [isPlay, isPlaying] = useState(0);
// load audio file on component load
useEffect(() => {
audioTune.load();
}, []);
// play audio sound
const playSound = () => {
audioTune.play();
isPlaying(1);
};
// pause audio sound
const pauseSound = () => {
audioTune.pause();
};
// stop audio sound
const stopSound = () => {
audioTune.pause();
audioTune.currentTime = 0;
isPlaying(0);
};
const handlePlaying = () => {
if (isPlay) {
stopSound();
} else {
playSound();
}
};
return (
<div>
<div className="App">
<button onClick={handlePlaying}>
{isPlay ? <Pause /> "pause" : <Play/> "listen to this page"}
</button>
</div>
</div>
);
}
export default AudioPlayer;
这里出现错误 {isPlay ? <Pause /> "pause" : <Play/> "listen to this page"}
错误是:
SyntaxError
/src/components/Audio2.js: Unexpected token, expected ":" (57:30)
我尝试在“”标记内插入图标,但这只是将按钮代码显示为字符串。
感谢您的帮助
你可以这样做
<button onClick={handlePlaying}>
{isPlay ? (
<>
<Pause /> Pause
</>
) : (
<>
<Play /> Listen to this page
</>
)}
</button>;