# CopyToClipboard
原生JS实现复制到剪贴板功能
const node = useRef<HTMLSpanElement>(null);
const CopyToClipboard = (ref: RefObject<HTMLElement>) => {
const inputElement: HTMLInputElement = document.createElement('input');
inputElement.value = ref.current?.innerText || '';
document.body.append(inputElement);
inputElement.select();
document.execCommand('copy');
inputElement.remove();
alert('copyed');
};
<span className="copy" ref={node} onClick={() => CopyToClipboard(node)}>text</span>
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# immer
produce精简语法
import { produce } from 'immer';
const nextState = produce(draftState => {
// 在这里对draftState进行修改
});
1
2
3
4
5
2
3
4
5
export default function App() {
const [number, setNumber] = useState(0);
const handleClick = () => {
setNumber(produce((draft) => (draft += 1)));
};
return (
<div className="App">
<button onClick={handleClick}>{number}</button>
</div>
);
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
完整的produce函数
produce(baseState, producer, patchListener)
baseState:表示当前的状态对象,即要进行修改的原始状态。producer:一个回调函数,用于对baseState进行修改。回调函数的参数是一个可变的draft对象,您可以在该对象上执行修改操作。patchListener(可选):一个回调函数,在每次对draft对象进行修改后被调用。该回调函数会接收一个描述本次修改的patches数组作为参数。
import produce from 'immer';
const currentState = { count: 0 };
const nextState = produce(currentState, draftState => {
return draftState.count += 1;
}, patches => {
console.log('Patches:', patches);
});
console.log('Current State:', currentState);
console.log('Next State:', nextState);
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12