杂谈
动态绑定函数
js
const hasEvents = mode === 'vertical' ? {
onMouseEvent: (e: React.MouseEvent) => { handelMouse(e, true) }
}
jsx
<div {...hasEvents} />
scss 的 each
scss
$theme-colors:
(
"primary": $primary,
"secondary": $secondary,
... // 还有很多
..
.
)
// 这样就不用把每一种颜色都写一遍了
@each $keys , $val in $theme-colors {
.icon-#{$key} { // 变量的写法
color: $val
}
}
项目中修改copy时的颜色
tex
一般我们copy时
颜色默认为蓝色
如果我们想要修改copy的颜色
应该怎么办呢
css
/*
在项目根目录 index.css 中
写
*/
::selection {
background: rgb(238, 162, 164); /* 你想修改的颜色 */
}
react 中使用@emotion css
jsx
/** @jsxImportSource @emotion/react */ // 必须在 import react 前 ; /** @jsx jsx */ 不管用
import { useState } from 'react';
import { css, jsx, Global, ClassNames } from '@emotion/react';
<div
css={css`
padding: 32px;
background-color: hotpink;
font-size: 24px;
border-radius: 4px;
&:hover {
color: ${color};
}
`}
>
Hover to change color.
</div>
<div
css={css`
width: 130px;
height: 20px;
color: green;
`}
>
123
</div>
<Global
styles={{
body: {
margin: 0,
padding: 0,
background: 'red',
},
}}
/>
<ClassNames>
{({ css, cx }) => (
<div
className={cx(
'some-class',
css`
color: yellow;
background: aliceblue;
`,
)}
>
some-class
</div>
)}
</ClassNames>
tex
相较以上方式,styled的用法似乎更好
jsx
import styled from "@emotion/styled";
const Pre = styled.pre`
text-align: left;
`;
<Pre>{ele[1]}</Pre>
tex
参考资料:
https://blog.csdn.net/qq_21567385/article/details/111590431
interface 的只读
ts
interface Person {
readonluy id : number;
name: string;
age?: number;
}
let franz : Person = {
id: 1,
name: 'franz'
}
// Cannot assign to 'id' because it is a read-only propertv. ts(2540)
franz.id = 2
泛型约束
ts
// 约束 传入的类型 只能是字符串 、数字
const func<T extends string | number> = () => {}
func('1')
另类类型断言
ts
// 这样就指定了参数在为字符串类型下,才执行特定操作
function getLenth(input: string | number) : number {
if ((<string>input).length) {
return (<string>input).length
}
}
interface 新奇定义方式
ts
interface Other {
(value: number) : number;
plus: (number: number[]) => number;
}
// use
Other(1);
Other.plus([1, 2, 3]);
交叉类型
tex
注意:
交叉类型不是交集
而是并集!
是把两个和为一个。
A & B
新版useDebounce
ts
import { useState, useEffect } from 'react'
function useDebounce(value: any, delay = 300) {
const [debouncedValue, setDebouncedValue] = useState(value)
useEffect(() => {
const handler = window.setTimeout(() => {
setDebouncedValue(value)
}, delay)
return () => {
clearTimeout(handler)
}
}, [value, delay])
return debouncedValue
}
export default useDebounce;
// use
const debouncedValue = useDebounce(inputValue, 300);
React.Children
tex
props.children 的值有 三种可能
当前组件没有子节点, 它就是 undefined;
有一个节点,数据类型是object;
如果有多个子节点,数据类型是array;
因此处理 props.children时要小心。
js
// 可以用 React.Children.map 来遍历子节点,而不用担心 props的数据类型是 undefined 还是 object
React.Children.map(props.children, (child) => child)
非空判断符,单个变量使用
js
// valuePropName?:string
controlProps[valuePropName!] = value // 过滤 valuePropName 为 undefined 的情况