useTextSelection
一个实用的 React Hook,提供 TextSelection 相关功能。
功能特性
- ✅ 核心功能: 提供 TextSelection 的核心功能
- ✅ 类型安全: 完整的 TypeScript 类型支持
- ✅ 易于使用: 简洁的 API 设计
- ✅ 性能优化: 高效的实现方式
- ✅ 自动清理: 组件卸载时自动清理资源
基本用法
typescript
import useTextSelection from "./useTextSelection";
function Component() {
const result = useTextSelection();
return <div>使用 useTextSelection</div>;
}高级用法
实际应用场景
typescript
function AdvancedComponent() {
const hookResult = useTextSelection(/* 参数 */);
// 根据具体 hook 的功能进行使用
return (
<div>
{/* 渲染内容 */}
</div>
);
}API 参考
useTextSelection(params?)
参数
根据具体 hook 的功能确定参数类型和说明。
返回值
根据具体 hook 的功能确定返回值类型和说明。
使用场景
- 场景一: 描述具体的使用场景
- 场景二: 描述另一个使用场景
- 场景三: 描述更多使用场景
注意事项
- 性能: 注意性能相关的使用建议
- 兼容性: 浏览器兼容性说明
- 最佳实践: 推荐的使用方式
兼容性
- ✅ React 16.8+
- ✅ TypeScript 4.0+
- ✅ 现代浏览器
- ✅ 服务端渲染 (SSR)
实现源码
查看 useTextSelection 的实现
tsx
import useEventListener from "../useHover/useEventListener";
import { useSafeState, useLatest } from "ahooks";
import type BasicTarget from "../../common/utils/BasicTarget";
interface RectProps {
top: number;
left: number;
bottom: number;
right: number;
height: number;
width: number;
}
interface StateProps extends RectProps {
text: string;
}
const initRect: RectProps = {
top: NaN,
left: NaN,
bottom: NaN,
right: NaN,
height: NaN,
width: NaN,
};
const initState: StateProps = {
text: "",
...initRect,
};
const getRectSelection = (selection: Selection | null): RectProps | {} => {
const range = selection?.getRangeAt(0);
if (range) {
const { height, width, top, left, right, bottom } =
range.getBoundingClientRect();
return { height, width, top, left, right, bottom };
}
return {};
};
const useTextSelection = (
target: BasicTarget | Document = document
): StateProps => {
const [state, setState] = useSafeState(initState);
const lastRef = useLatest(state);
useEventListener(
"mouseup",
() => {
if (!window.getSelection) return;
const select = window.getSelection();
const text = select?.toString() || "";
if (text) setState({ ...state, text, ...getRectSelection(select) });
},
target
);
useEventListener(
"mousedown",
() => {
if (!window.getSelection) return;
if (lastRef.current.text) setState({ ...initState });
const select = window.getSelection();
select?.removeAllRanges();
},
target
);
return state;
};
export default useTextSelection;