说明:这篇文章主要用于记录前端开发时遇到的一些小问题。
1.变量拼接字符和给数组元素加上双引号
“‘”+bianliang+"'"=>'bianlaing'
a=15
“‘”+a+'+%+'+"'"=>'15%'
//给数组元素加上双引号
let array = []
data.map((item)=>{
let strItem = ""+item+""
array.push(strItem)
})
console.log(array)
2.moment实现计算时间差
先用时间字符串初始化moment对象,使用unix()将moment对象转化为时间戳
moment('时间字符串').unix()
moment()获取当前对象
moment(record.endTime).unix() - moment().unix()
day = moment(record.endTime).diff(moment(), 'day');
获取两个时间之前相差的天数:
//获取当前时间
let m1 = moment();
//获取需要对比的时间
let m2 = moment(time);
//计算相差多少天 day可以是second minute
day = m2.diff(m1, 'day');
3.css样式
'Index show' : 'Index'
Index和show样式共同生效 Index单独生效
.Index{
}
.show{
}
4.父组件调用子组件的方法
法一:函数组件的hook方式
父组件:
1.使用const childRef =React.creatRef() 创建后传给子组键使用,
也供自己调用子组件时使用
2.<Child onRef = {childRef} />
3.父组件使用 childRef.current.子组件方法名();
(对应Cancel,则可调用Cancel)
父组件代码【这个是在Modal中表单提交时,取消操作要清空表单已填入的数据的实例】:
子组件代码:
父组件Modal取消操作要调用子组件的onReset方法;
5.获取树形数组中特定元素的所在层级
const treeData = [
{
title: "Node1",
value: "0-0",
key: "0-0",
children: [
{
title: "Child Node1",
value: "0-0-1",
key: "0-0-1",
children: [
{
title: "Child Node1-1",
value: "0-0-1-1",
key: "0-0-1-1",
}
]
},
{
title: "Child Node2",
value: "0-0-2",
key: "0-0-2"
}
]
},
{
title: "Node2",
value: "0-1",
key: "0-1"
}
];
//这部分代码用于计算所选节点所在层数
const valueMap = {};
const loops = (list, parent) => {
return (list || []).map(({ children, value }) => {
const node = (valueMap[value] = {
parent,
value
});
node.children = loops(children, node);
return node;
});
}
loops(treeData);
const getPath = (value) => {
const path = [];
let current = valueMap[value];
while (current) {
path.unshift(current.value);
current = current.parent;
}
return path;
}
//上面的函数是单独的部分,可用于提取树形数组选择的路径
const onChange = value => {
console.log("Change", getPath(value));
console.log("Change", getPath(value).length);
};
6.Hook useEffect
每次我们重新渲染,都会生成新的 effect,替换掉之前的。某种意义上讲,effect 更像是渲染结果的一部分 —— 每个 effect “属于”一次特定的渲染。
7.
height: calc(100vh - 80px);
表示div高度设置为浏览器高度减去80px