简单问题记录,方便回顾
- Q:react项目img图片在ios上不渲染问题 A:img标签外包一层div设置对应宽高,img {width: 100%, height: 100%},或者使用背景图
div {width: 50px; height:50px}
img {width: 100%; height: 100%}
- Q: react-ts下input事件event的类型
const handlerChange = (event: React.ChangeEvent<HTMLInputElement>) => {
event.persist();
// 获取当前event事件的dom元素
})
- ts的断言与泛型:
断言:当参数是联合参数或者需要更改其类型时,可以使用断言方法把参数指定为你想要的类型
function getLength( arg : number | string) {
// 因为参数是联合参数,所以此处会报错,
if (arg.length) {
return arg.length;
}
// 断言,把此处arg转换为string类型
if ((<string>arg).length)) {
return arg.length
}
}
interface Props{
pageSize: number,
pageNum: number
}
function getList (params: Props) {
API.post.request(params)
....
}
//当已经定义类型的参数需要额外传参时,如果不断言,就会报错
getList({pageSize: 1, pageNum: 2, name: '123'})
interface NewProps extends Props {
name: string
}
getList({pageSize: 1, pageNum: 2, name: '123'} as NewProps)
泛型函数: 默认不指定函数的参数类型,在使用时根据参数生成类型,提高函数的复用性,
// 正常函数指定了参数类型后,传入不匹配的参数会报错
// 如果指定参数类型为any,则无法控制返回参数类型
function getItem(arg: number) {
return arg;
}
getItem('1')
// 泛型函数可以捕获传入参数的类型,
// 之再次使用了 T当做返回值类型。现在我们可以知道参数类型与返回值类型是相同的了
function getItem<T>(arg: T): T {
return arg;
}
getItem(1);
getItem('2');
4.模拟下载文件
// 下载excel
export const downloadExcell = (data: any, fileType: string = 'xls', fileName?: string) => {
const blob = new Blob([data], {
type: 'application/vnd.ms-excel;charset=utf-8',
});
const filename = `${fileName || 'excel-' + Date.now() / 1000}.${fileType}`;
if ('download' in document.createElement('a')) {
const downloadElement = document.createElement('a');
let href = '';
if (window.URL) href = window.URL.createObjectURL(blob);
else href = window.webkitURL.createObjectURL(blob);
downloadElement.href = href;
downloadElement.download = filename;
document.body.appendChild(downloadElement);
downloadElement.click();
if (window.URL) window.URL.revokeObjectURL(href);
else window.webkitURL.revokeObjectURL(href);
document.body.removeChild(downloadElement);
} else {
navigator.msSaveBlob(blob, filename);
}
};
5.react项目中模拟锚点跳转,因为a标签会触发路由跳转,所以需要使用h5新增的API
const areaPosition = (anchor: string) => {
if (anchor) {
// 找到锚点
let anchorElement = document.getElementById(anchor);
anchorElement && anchorElement.scrollIntoView({block: 'start', behavior: 'smooth'});
}
}