模版字符串原理
之前我们都是使用字符串拼接的方式来写,这样稍不注意就会写错,
es6新出了模版字符串 ,以 ``的形式,
其中可以以${}的方式动态表示变量。
let name="张三",age="18";
let str=`${name} 今年 ${age} 岁了`
原理
let name = "若薇";
let age = 18;
let str = "${name}今年${age}岁了";
function muban(str) {
let regex = /\$\{([^}]+)\}/g;
return str.replace(regex, function (match, key, c, d) {
return eval(key);
});
}
console.log("muban(str)", muban(str));
参考资料
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/replace#%E6%8C%87%E5%AE%9A%E4%B8%80%E4%B8%AA%E5%87%BD%E6%95%B0%E4%BD%9C%E4%B8%BA%E5%8F%82%E6%95%B0
https://blog.csdn.net/qq_40028324/article/details/116492586
https://www.jianshu.com/p/e78a1e25f02b
解决重渲后歌曲当前播放时间置为0问题
useEffect(() => {
if (musicRef.current) {
const { currentTime } = musicRef.current;
if (currentTime) {
localStorage.setItem("currentTime", currentTime);
}
if (
play &&
currentTime === 0 &&
Number(localStorage.getItem("currentTime"))
) {
musicRef.current.currentTime = Number(
localStorage.getItem("currentTime")
);
musicRef.current.play();
console.log("再赋值", musicRef.current.currentTime);
}
}
return () => {
removeEventListener("load", listenFunc);
};
});
react 歌词滚动
useMemo(() => {
const timeArr: any = [];
const lrcArr: any = [];
const regex = /\[(\d{2}:\d{2})\.\d{2,3}\](.+)/g;
let tmp = regex.exec(lyric);
while (tmp) {
timeArr.push(tmp[1]);
lrcArr.push(tmp[2]);
tmp = regex.exec(lyric);
}
setLrc(lrcArr);
const index = timeArr.findIndex((item: any) => {
return item === time;
});
const div = document.getElementById("lyricdiv");
if (index !== -1 && div) {
div.style.top = -index * 3.5 + 15 + "rem";
[...div.children].forEach((item) => {
if (item) {
item.className = "";
}
});
if (div.children[index]) {
div.children[index].className = "active";
}
}
}, [lyric, time]);
<Lyric>
<ul id="lyricdiv">
{lrc.map((item: any, index: number) => (
<li key={index}>{item}</li>
))}
</ul>
</Lyric>
const Lyric = styled.div`
width: calc(100% - 30rem);
overflow-y: auto;
position: relative;
font-size: 1.4rem;
text-align: center;
ul {
width: 100%;
position: absolute;
top: 15rem;
li {
margin-bottom: 1.5rem;
height: 2rem;
list-style: none;
width: 100%;
line-height: 2rem;
}
}
`;