自定义hook
封装hook,但是文件名,函数名,要用useXyz这种,一个简单的自定义hook如下:
import { useState } from "react";
const useTags = () => {
const [tags, setTags] = useState<string[]>(['衣', '食', '住', '行']);
return {tags, setTags};
}
export {useTags};
React Route 之 react
Link标签
<Link to={'/tags/' + tag}>
<span className={"oneLine"}>{tag}</span>
<Icon name={"right"}/>
</Link>
在react router v6 中,不再有exact,默认就是精确匹配优先
React Route获取参数
路由中这样写
<Route path="/tags/:id" element={<Tag/>}/>
这样传递
<Link to={'/tags/' + tag.id}>
<span className={"oneLine"}>{tag.id}{`-`}{tag.name}</span>
<Icon name={"right"}/>
</Link>
获取参数
type Params = {
id: string;
}
const Tag: React.FunctionComponent = (props) => {
let { id: idString } = useParams<Params>();
return (<div>hi</div>);
}
封装可以带ref的函数组件
type Props = {
label: string;
children?: React.ReactNode;
} & React.InputHTMLAttributes<HTMLInputElement>;
const Input = React.forwardRef((props: Props, ref: LegacyRef<HTMLInputElement>) => {
const { label, children, ...rest } = props;
return (<Wrapper>
<span>{label}</span>
<input {...rest} ref={ref}/>
</Wrapper>);
});
其中,InputHTMLAttributes表示集成input的属性
React.forwardRef是一种封装,让组件可以接受ref参数
形参ref后面要指出类型,LegacyRef<HTMLInputElement>,这是根据webstorm提示写的
使用函数组件:
return (<Wrapper>
<Input label={"备注"}
ref={inputRef}
placeholder={"请填写备注"}
defaultValue={notes}
onBlur={(e) => {
if (inputRef && inputRef.current) {
props.onChange(inputRef.current.value);
}
}}/>
</Wrapper>);
函数组件的参数类型声明
// 声明参数的类型,类似于java中的实体类
type Props = {
name: string;
} & React.BaseHTMLAttributes<HTMLBaseElement>
实在不知道声明什么类型时,声明一个基础类型React.BaseHTMLAttributes<HTMLBaseElement>,当然也可以猜,svg标签猜出来是这个
type Props = {
name: string;
} & React.SVGAttributes<SVGElement>
const Icon = (props: Props) => {
const { name, ...rest } = props;
return (<svg className={"icon"} {...rest}>
{/*其中money是id,就等于文件名*/}
<use xlinkHref={'#' + props.name}/>
</svg>);
}
react router v6 的history
// This is a React Router v6 app
import { useNavigate } from "react-router-dom";
function App() {
const navigate = useNavigate();
return (
<>
<button onClick={() => navigate(-2)}>返回2个页面</button>
<button onClick={() => navigate(-1)}>返回</button>
<button onClick={() => navigate(1)}>前进</button>
<button onClick={() => navigate(2)}>前进2个页面</button>
</>
);
}
其他
- 选中加标签 ctrl+alt+t ,然后选择 surround with tag