壹
一个改变颜色的Hook
import React from "react";
import useRandomColor from "./useRandomColor";
const Hook = () => {
const [color, changeColor] = useRandomColor(["red", "blue", "green"], "red");
return (
<>
<h1 style={{ color: color }}>try to change my color</h1>
<button onClick={changeColor}>change color</button>
</>
);
};
export default Hook;
hook:
import React, { useState, useEffect } from "react";
const useRandomColor = (colors, initColor) => {
const [color, setColor] = useState(initColor);
const changeColor = () => {
const randomIndex = Math.floor(Math.random() * colors.length);
setColor(colors[randomIndex])
};
return [color, changeColor];
};
export default useRandomColor
贰
在不需要利用state保存数据的场景(如一次性提交的非受控表单),可以封装一个ref hook。
import React, { useRef, useState } from "react";
const useRefForm = (formName, initialValue = {}) => {
const value = useRef(initialValue);
const [, setCount] = useState(0);
const onChange = (key, val) => {
// 更新某个key
if (typeof key === "string") {
value.current[key] = val;
} else {
// 传入一个对象 整个更新
value.current = { ...value.current, ...key };
}
};
const onUpdate = (key, val) => {
// 更新某个key
if (typeof key === "string") {
value.current[key] = val;
} else {
// 传入一个对象 整个更新
value.current = { ...value.current, ...key };
}
// 触发渲染
setCount((c) => c + 1);
};
return {
[formName]: value.current,
onChangeForm: onChange,
onUpdateForm: onUpdate,
};
};
export default useRefForm;
use
const { holderInfo, onChangeForm, onUpdateForm } = useRefForm("holderInfo", {
user_name: "",
mobile: "",
cert_type: 10,
cert_id: ""
});
// 会更新holderInfo,但不会重新渲染,可用于非受控的input
<input name="mobile" onInput={(v)=>onChangeForm("mobile",v)}/>
// 更新holderInfo且重新渲染
<input name="mobile" onInput={(v)=>onUpdateForm("mobile",v)}/>
注:需要更新视图可调用onUpdateForm
叁
…