# @getsoren/react-utils 中文文档

规范地址：https://npmcn.com/package/%40getsoren/react-utils/

版本：1\.38\.0
npm 元数据更新时间：2026-11-14T01:11:43.735Z
中文译文更新时间：2026-11-16T06:50:08.726Z
软件包许可：ISC

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40getsoren/react-utils
原文对照：https://npmcn.com/package/%40getsoren/react-utils/?lang=original
项目主页：https://github.com/getsoren/react-utils#readme
源码仓库：https://github.com/getsoren/react-utils

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：77.3 kB，67 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：0 个
- peer 依赖：react \>=18\.0\.0，react-dom \>=18\.0\.0
- 首次发布：2026-05-15T22:03:00.855Z
- 最新版本发布：2026-11-14T01:11:43.543Z
- 近 30 天下载量：14431（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：13（近 12 个月 13 个）

## 中文简介

反应数据表和反应数据网格

## 安装

```sh
npm install @getsoren/react-utils
```

也可以使用：`pnpm add @getsoren/react-utils`、`yarn add @getsoren/react-utils`、`bun add @getsoren/react-utils`

## README

# @ getsoren/ react- utils

[![License: ISC](https://img.shields.io/badge/License-ISC-blue.svg)](https://opensource.org/licenses/ISC)

> 综合收集现代反应公用设施与定制钩子 加快你开发工作流程.

## \* 安装

```bash
# bun
bun add @getsoren/react-utils

# npm
npm install @getsoren/react-utils

# yarn
yarn add @getsoren/react-utils

# pnpm
pnpm add @getsoren/react-utils
```

## QQ 快速启动

```typescript
import { useInputState, capitalize, phoneNumberAdapter } from '@getsoren/react-utils';

function App() {
  const [email, onEmailChange] = useInputState('');
  const [phone, onPhoneChange] = useInputState('');

  return (
    <form>
      <input 
        type="email" 
        value={email} 
        onChange={onEmailChange}
        placeholder={capitalize('email address')}
      />
      <input 
        type="tel" 
        value={phoneNumberAdapter(phone)} 
        onChange={onPhoneChange}
        placeholder="Phone number"
      />
    </form>
  );
}
```

## API 文档

### 钩子

#### `useLocalStorage(key, initialValue?, options?)`

以自动同步管理本地Storage中的数据持久性.

```typescript
const [user, setUser, removeUser] = useLocalStorage('user', { name: '', email: '' });

// With custom options
const [data, setData] = useLocalStorage('data', [], {
  serializer: JSON.stringify,
  deserializer: JSON.parse
});
```

**参数:**

-   `key`: 本地密钥
-   `initialValue`: 初始值(可选)
-   `options`: 序列化选项(可选)

**回返情况:** `[value, setValue, removeValue]`

* * *

#### `useSessionStorage(key, initialValue?, options?)`

与 API 相同 `useLocalStorage`,但以会话Storage为后盾:该值在组件未挂载和页面重载后存活,并在分页关闭时清除。 适合草稿和其他瞬间状态.

```typescript
const [draft, setDraft, removeDraft] = useSessionStorage('form-draft', { title: '' });

// Persist as the user types…
setDraft({ title: 'My title' });

// …and clear it once submitted
removeDraft();
```

**参数:**

-   `key`: 会话组合键
-   `initialValue`: 初始值(可选)
-   `options`: 序列化选项(可选)

**回返情况:** `[value, setValue, removeValue]`

* * *

#### `useInputState(initialValue)`

用自动事件处理简化输入状态管理.

```typescript
const [name, onNameChange] = useInputState('');
const [isChecked, onCheckChange] = useInputState(false);

<input type="text" value={name} onChange={onNameChange} />
<input type="checkbox" checked={isChecked} onChange={onCheckChange} />
```

* * *

#### `useDebounce(value, delayOrOptions)`

延迟执行一个值,以防止拨打过多.

```typescript
// Simple usage
const debouncedSearchTerm = useDebounce(searchTerm, 500);

// With callback
const debouncedValue = useDebounce(inputValue, {
  delay: 300,
  onDebounce: (value) => console.log('Debounced:', value)
});
```

* * *

#### `useDebouncedFn(callback, delay?)`

创建调用函数的已取消版本.

```typescript
const debouncedSearch = useDebouncedFn((query: string) => {
  fetchSearchResults(query);
}, 500);

// Will only execute after user stops typing for 500ms
debouncedSearch(inputValue);
```

**参数:**

-   `callback`: 跳出函数
-   `delay`: 以毫秒计的延迟( 默认值 : `300`(中文(简体) )

**回返情况:** 已取消的回调版本

* * *

#### `useToggle(initialState?)`

以切换功能管理布尔状态 .

```typescript
const [isOpen, toggle, setIsOpen] = useToggle(false);

<button onClick={toggle}>
  {isOpen ? 'Close' : 'Open'}
</button>
```

* * *

#### `useWindowSize()`

实时跟踪窗口尺寸.

```typescript
const { width, height } = useWindowSize();

return (
  <div>
    Size: {width}x{height}
  </div>
);
```

* * *

#### `useInView(ref, options?)`

检测某一元素在视图中是否可见.

```typescript
const ref = useRef(null);
const isInView = useInView(ref, {
  threshold: 0.5,
  triggerOnce: true
});

<div ref={ref}>
  {isInView ? 'Visible!' : 'Not visible'}
</div>
```

* * *

#### `useDocumentTitle(title)`

公开管理文档标题.

```typescript
const { setTitle, title } = useDocumentTitle('My App');

// Change title dynamically
setTitle('New Page');
```

* * *

#### `useHasCamera()`

说明设备是否能够从文件输入中取相:带有相机的触摸设备(手机,平板电脑). 计算机的网络相机不计数, 因为浏览器忽略 `capture` 在这里.

```typescript
const hasCamera = useHasCamera();

{hasCamera && <input type="file" accept="image/*" capture="environment" />}
```

* * *

#### `useEventListener(eventName, handler, element?, options?)`

添加自动清理的事件听众 .

```typescript
const buttonRef = useRef(null);

useEventListener('click', () => console.log('Clicked!'), buttonRef);
useEventListener('keydown', handleKeyDown); // window by default
```

* * *

#### `useScript(src, options?)`

公开装入外部脚本.

```typescript
const status = useScript('https://example.com/script.js', {
  position: 'body-end',
  enable: true
});

// status: 'idle' | 'loading' | 'ready' | 'error'
```

* * *

#### `useIntersectionObserver(elementRef, options)`

高级相交观察钩用于复杂能见度检测.

```typescript
const elementRef = useRef(null);
const entry = useIntersectionObserver(elementRef, {
  threshold: 0.1,
  freezeOnceVisible: true
});

const isVisible = entry?.isIntersecting;
```

* * *

#### `useIsMounted()`

返回一个函数以检查组件是否仍然挂载 .

```typescript
const isMounted = useIsMounted();

useEffect(() => {
  fetchData().then(data => {
    if (isMounted()) {
      setData(data);
    }
  });
}, []);
```

* * *

#### `useIsomorphicLayoutEffect(effect, deps?)`

安全部门改革安全版本 `useLayoutEffect` 这回回到 `useEffect` 在服务器上.

```typescript
useIsomorphicLayoutEffect(() => {
  // Runs synchronously after DOM mutations on client
  // Falls back to useEffect on server
  measureElement();
}, [dependency]);
```

* * *

#### `useAudio(src, options?)`

以对播放、暂停、音量和进度跟踪的全面控制来管理音频播放.

```typescript
const [time, setTime] = useState(0);
const [duration, setDuration] = useState(0);

const { isPlaying, volume, play, pause, toggle, stop, setVolume } = useAudio('/audio/song.mp3', {
  volume: 0.8,
  loop: true,
  autoPlay: false,
  onTimeUpdate: setTime,
  onLoadedMetadata: setDuration,
});

<button onClick={toggle}>{isPlaying ? 'Pause' : 'Play'}</button>
<span>{time}s / {duration}s</span>
<input type="range" min={0} max={1} step={0.1} value={volume} onChange={(e) => setVolume(Number(e.target.value))} />
```

**参数:**

-   `src`: 音频源 URL
-   `options.volume`: 从 0 到 1 的初始卷( 默认 : `1`(中文(简体) )
-   `options.loop`: 回放循环( 默认 ): `false`(中文(简体) )
-   `options.autoPlay`: 负载时自动播放( 默认 ): `false`(中文(简体) )
-   `options.onTimeUpdate`: 以当前播放时间在秒内发射回调
-   `options.onLoadedMetadata`: 装入元数据时, 以秒计的全长调用

**回返情况:** `{ isPlaying, volume, error, play, pause, toggle, stop, setVolume }`

### 水电费

#### 类型验证

```typescript
import { isArray, isObject, isString, isNumber, isBoolean, isFunction, isRef } from '@getsoren/react-utils';

if (isArray(data)) {
  // TypeScript knows data is an array
  console.log(data.length);
}

if (isObject(value)) {
  // TypeScript knows value is an object
  console.log(Object.keys(value));
}
```

#### 对象操纵

```typescript
import { removeObjectProperty, isDeepEqualObject, getObjectValue } from '@getsoren/react-utils';

// Remove property without mutation
const newObj = removeObjectProperty(originalObj, 'propertyToRemove');

// Deep comparison of objects
const areEqual = isDeepEqualObject(obj1, obj2);

// Get nested value with dot notation
const obj = { car: { color: { black: 'dark' } } };
getObjectValue(obj, 'car.color.black');              // "dark"
getObjectValue(obj, 'car.color.red', 'not found');   // "not found"
```

#### 字符串操纵

```typescript
import { capitalize, capitalizeWords, upperFirst } from '@getsoren/react-utils';

capitalize('hello world');     // "Hello world"
capitalizeWords('hello world'); // "Hello World"
upperFirst('pEMP 12m');        // "PEMP 12m" — the rest kept as written, unlike capitalize
```

#### 数量转换

```typescript
import { toNumberOrZero } from '@getsoren/react-utils';

toNumberOrZero('42');    // 42
toNumberOrZero('abc');   // 0
toNumberOrZero(null);    // 0
toNumberOrZero(true);    // 0 (booleans return 0)
```

#### 小数输入

十进制字段持有有分数并显示为用户语言所写.

```typescript
import { formatDecimal, getDecimalSeparator, toDecimalInput } from '@getsoren/react-utils';

// What the field keeps of what is typed: digits and one separator, a typed comma held as a point
toDecimalInput('12,5');        // "12.5"
toDecimalInput('12,345', 2);   // "12.34" — two decimals at most
toDecimalInput('1 200 €');     // "1200"

// What the field shows: the held or stored number, written as the language does
formatDecimal('12.5', 'fr');   // "12,5"
formatDecimal('12.', 'fr');    // "12," — while it is typed too
formatDecimal('12.5', 'en');   // "12.5"
formatDecimal('n/a', 'fr');    // "n/a" — any other text is kept as it is

getDecimalSeparator('fr');     // ","
getDecimalSeparator('en');     // "."

<input
  inputMode="decimal"
  value={formatDecimal(amount, language)}
  onChange={({ target }) => setAmount(toDecimalInput(target.value, 2))}
/>
```

#### 平台检测

```typescript
import { isMac } from '@getsoren/react-utils';

// Detects macOS at runtime (SSR-safe: returns false on the server)
const shortcut = isMac() ? '⌘ + K' : 'Ctrl + K';
```

**回返情况:** `boolean` —— 说 `true` 当运行在macOS上, `false` 否则.

### 适应器

#### `phoneNumberAdapter(phoneNumber, options?)`

按照国际标准格式化电话号码.

```typescript
// Supported formats
phoneNumberAdapter('0123456789');              // "01 23 45 67 89" (France)
phoneNumberAdapter('441234567890');            // "1234 567 890" (UK)
phoneNumberAdapter('1234567890');              // "(123) 456-7890" (US)

// With international prefix
phoneNumberAdapter('33123456789', { addPrefix: true });  // "+33 01 23 45 67 89"

// Custom separator
phoneNumberAdapter('0123456789', { separator: '-' });    // "01-23-45-67-89"
```

**支助国家:**

| 代码 | 国家 | 格式 |
| --- | --- | --- |
| 33个 | 法国 | 01 23 45 67 89 |
| 第44条 | 联合王国 | 1234 567 890 (简体中文) |
| 第49条 | 德国 | 0151 234 56789 (中文(简体) ) |
| 页:1 | 页:1 | 987 654 321 (中文(简体) ) |
| 1个 | 美国 | (123) 456-7890 |

* * *

#### `priceAdapter(value, options?)`

按地产地和货币编制价格.

```typescript
priceAdapter(1000);                           // "1 000 €"
priceAdapter(1000.50);                        // "1 000,50 €"
priceAdapter(500, { local: 'en-US' });       // "€500"
priceAdapter('-');                            // "-€"
priceAdapter(null);                           // "0 €"
```

**选项 :**

-   `local`: 语言字符串( 默认为 “fr- FR ”)
-   `currency`: 货币代码( 默认为 “ EUR ”)
-   `style`: 数字格式样式( 默认: “ 货币 ” )

* * *

#### `formatCreditCardNumber(number, maxLength?)`

格式化有适当间隔的信用卡号码.

```typescript
formatCreditCardNumber('1234567890123456');   // "1234 5678 9012 3456"
formatCreditCardNumber('1234567890123456', 15); // "1234 5678 9012 3"
formatCreditCardNumber(1234567890123456);     // "1234 5678 9012 3456"
```

* * *

#### `addressToString(address)`

将地址对象转换为格式化的字符串.

```typescript
const address = {
  streetNumber: 82,
  route: 'Chemin de cafon 2',
  postalCode: '83720',
  city: 'Trans en provence',
  country: 'France'
};

addressToString(address); // "82 Chemin de cafon 2, 83720 Trans en provence, France"

// Partial addresses work too
addressToString({ city: 'Paris', country: 'France' }); // "Paris, France"
```

* * *

#### `getInitials(name, capitalize?)`

从名称中取出首字母.

```typescript
// With a string
getInitials('John Doe');                                    // "JD"

// With first and last name
getInitials({ firstName: 'John', lastName: 'Doe' });        // "JD"

// With full name
getInitials({ fullName: 'John Doe Smith' });               // "JD"

// With forced capitalization
getInitials({ firstName: 'john', lastName: 'doe' }, true); // "JD"
getInitials({ firstName: 'john', lastName: 'doe' }, false); // "jd"
```

## 使用实例

### 完整联系表

```typescript
import React from 'react';
import {
  useInputState,
  useToggle,
  phoneNumberAdapter,
  capitalize,
  formatCreditCardNumber
} from '@getsoren/react-utils';

function ContactForm() {
  const [name, onNameChange] = useInputState('');
  const [email, onEmailChange] = useInputState('');
  const [phone, onPhoneChange] = useInputState('');
  const [cardNumber, onCardChange] = useInputState('');
  const [acceptTerms, toggleTerms] = useToggle(false);

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log({
      name: capitalize(name),
      email,
      phone: phoneNumberAdapter(phone, { addPrefix: true }),
      cardNumber: formatCreditCardNumber(cardNumber)
    });
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        placeholder="Full name"
        value={name}
        onChange={onNameChange}
      />
      
      <input
        type="email"
        placeholder="Email"
        value={email}
        onChange={onEmailChange}
      />
      
      <input
        type="tel"
        placeholder="Phone"
        value={phoneNumberAdapter(phone)}
        onChange={onPhoneChange}
      />
      
      <input
        placeholder="Card number"
        value={formatCreditCardNumber(cardNumber)}
        onChange={onCardChange}
        maxLength={19}
      />
      
      <label>
        <input
          type="checkbox"
          checked={acceptTerms}
          onChange={toggleTerms}
        />
        I accept the terms
      </label>
      
      <button type="submit" disabled={!acceptTerms}>
        Submit
      </button>
    </form>
  );
}
```

### 以跳动来搜索钩

```typescript
import React, { useEffect, useState } from 'react';
import { useDebounce, useInputState } from '@getsoren/react-utils';

function SearchComponent() {
  const [query, onQueryChange] = useInputState('');
  const [results, setResults] = useState([]);
  const [loading, setLoading] = useState(false);
  
  const debouncedQuery = useDebounce(query, {
    delay: 300,
    onDebounce: () => setLoading(true)
  });

  useEffect(() => {
    if (debouncedQuery) {
      // Simulate API call
      fetch(`/api/search?q=${debouncedQuery}`)
        .then(res => res.json())
        .then(data => {
          setResults(data);
          setLoading(false);
        });
    } else {
      setResults([]);
      setLoading(false);
    }
  }, [debouncedQuery]);

  return (
    <div>
      <input
        placeholder="Search..."
        value={query}
        onChange={onQueryChange}
      />
      
      {loading && <div>Searching...</div>}
      
      <ul>
        {results.map(item => (
          <li key={item.id}>{item.title}</li>
        ))}
      </ul>
    </div>
  );
}
```

### 可见度检测

```typescript
import React, { useRef } from 'react';
import { useInView, useIntersectionObserver } from '@getsoren/react-utils';

function VisibilityExample() {
  const simpleRef = useRef(null);
  const advancedRef = useRef(null);
  
  // Simple visibility detection
  const isSimpleInView = useInView(simpleRef, {
    threshold: 0.5,
    triggerOnce: true
  });
  
  // Advanced intersection observer
  const entry = useIntersectionObserver(advancedRef, {
    threshold: [0, 0.25, 0.5, 0.75, 1],
    rootMargin: '50px'
  });

  return (
    <div>
      <div ref={simpleRef} style={{ height: '100px', marginTop: '1000px' }}>
        {isSimpleInView ? '✅ Simple: Visible' : '❌ Simple: Hidden'}
      </div>
      
      <div ref={advancedRef} style={{ height: '100px', marginTop: '1000px' }}>
        Advanced: {entry?.intersectionRatio.toFixed(2) || 0}% visible
      </div>
    </div>
  );
}
```

## 测试

该图书馆与Vitest进行了全面测试. 进行测试:

```bash
# Unit tests
bun run test

# Coverage report
bun run coverage

# Lint code
bun run lint
```

## QQ 类型脚本支持

所有公用设施和车钩都用TypeScript完全打入. 类型会自动推断:

```typescript
const [count, setCount] = useLocalStorage('count', 0); // count is number
const [user, setUser] = useLocalStorage('user', { name: '', age: 0 }); // user is typed

// Type guards work perfectly
if (isArray(data)) {
  data.map(item => item); // TypeScript knows data is an array
}

if (isString(value)) {
  value.toUpperCase(); // TypeScript knows value is a string
}
```

## 所需经费

-   反应 : 18.0.0
-   反应 DOM : 18.0.0
-   包含类型脚本支持

## \* 特性

-   ✅ **完全输入** 有类型脚本
-   ✅ **树能震动** - 只导入你需要的东西
-   ✅ **SSR 兼容** - 与Next.js,Gatsby等合作.
-   ✅ **轻巧** - 最小捆绑撞击
-   ✅ **测试的很好** - 综合测试套房
-   ✅ **现代** - 使用最新的反应模式
-   ✅ **注重业绩** - 最佳钩和公用事业

## 捐款

欢迎捐款! 请检查我们 [贡献指南](https://npmcn.com/package/%40getsoren/react-utils/CONTRIBUTING.md)。 。 。 .

1.  叉子项目
2.  创建您的特性分支( E)`git checkout -b feature/AmazingFeature`(中文(简体) )
3.  提交更改( E)`git commit -m 'Add some AmazingFeature'`(中文(简体) )
4.  推向分行(`git push origin feature/AmazingFeature`(中文(简体) )
5.  打开拉请求

## 许可证

这个项目根据ICC许可证颁发许可证。 见 [自由主义](https://npmcn.com/package/%40getsoren/react-utils/LICENSE) 详细文件.

## 关键词

-   反应
-   反应钩
-   公用事业
-   类型脚本
-   业绩
-   开发者经验
-   表格处理
-   州管理层

## ++ 辅助

-   🐛 [报告错误](https://github.com/getsoren/react-utils/issues)
-   💡 [请求特性](https://github.com/getsoren/react-utils/issues)
-   📖 [文档](https://github.com/getsoren/react-utils#readme)
-   💬 [讨论情况](https://github.com/getsoren/react-utils/discussions)

## 接下来呢?

我们不断改善! 即将到来的特性 :

-   \* 更多形式公用事业
-   \* 移动专用钩
-   动画助手
-   数据操作公用事业

* * *

由 QQ 创建 [米卡埃尔·奥斯托尼](https://github.com/MickaelAustoni)

## 常见问题

### @getsoren/react-utils 是什么？

反应数据表和反应数据网格

### 如何安装 @getsoren/react-utils？

在项目目录运行 npm install @getsoren/react-utils，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：react（\>=18\.0\.0）、react-dom（\>=18\.0\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @getsoren/react-utils 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @getsoren/react-utils 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @getsoren/react-utils 可以商用吗？

@getsoren/react-utils 使用 ISC 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @getsoren/react-utils 的下载量有多少？

根据 npm 官方下载统计，@getsoren/react-utils 在 2026/10/17 – 2026/11/15 这 30 天内被下载 14,431 次，日均约 481 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @getsoren/react-utils 还在维护吗？

最新版本 1\.38\.0 发布于 2026/11/14（2 天前）；至今共发布 13 个版本，其中过去 12 个月发布了 13 个；首次发布于 2026/05/16。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

