Skip to content

Conversation

@betterhyq
Copy link

@betterhyq betterhyq commented Aug 20, 2025

🤔 这个变动的性质是?

  • 新特性提交
  • 日常 bug 修复
  • 站点、文档改进
  • 演示代码改进
  • 组件样式/交互改进
  • TypeScript 定义更新
  • 包体积优化
  • 性能优化
  • 功能增强
  • 国际化改进
  • 重构
  • 代码风格优化
  • 测试用例
  • 分支合并
  • 其他改动(是关于什么的改动?)

🔗 相关 Issue

@nutui/nutui-react-taro在h5点应用场景下,如果直接获取Taro组件库的Input元素调用focus方法会失效,应为Taro在外层保留一个taro-input-core
image

💡 需求背景和解决方案

解决h5环境下无法正确获取input原生标签

☑️ 请求合并前的自查清单

⚠️ 请自检并全部勾选全部选项⚠️

  • 文档已补充或无须补充
  • 代码演示已提供或无须提供
  • TypeScript 定义已补充或无须补充
  • fork仓库代码是否为最新避免文件冲突
  • Files changed 没有 package.json lock 等无关文件

Summary by CodeRabbit

  • 新增功能
  • Bug 修复
    • 修复 Web 环境下输入框无法正确聚焦/失焦的问题,提升跨平台聚焦行为一致性,减少无法唤起软键盘等异常。
  • 重构
    • 统一各平台对输入框聚焦/失焦的处理逻辑,改善稳定性与可维护性,不改变公开接口与使用方式。

@coderabbitai
Copy link

coderabbitai bot commented Aug 20, 2025

Walkthrough

在 Taro 版 Input 中新增 getNativeInput(),用于在 WEB 环境定位包裹内的原生 input;非 WEB 环境返回现有 ref。将原先直接对 inputRef 调用 focus/blur 的代码改为对 getNativeInput() 返回的原生元素调用。无对外 API 变更。

Changes

Cohort / File(s) Summary
Input 原生元素访问与聚焦逻辑
src/packages/input/input.taro.tsx
新增 getNativeInput() 以统一获取原生 input;在 WEB 环境查找容器内的实际 input 元素,其他环境返回 ref.current;将 focus()/blur() 的调用改为作用于 getNativeInput() 返回的元素(使用可选链保护);未修改导出或公共声明。

Sequence Diagram(s)

sequenceDiagram
    participant U as 用户
    participant Input as Input(Taro)
    participant G as getNativeInput()
    participant N as 原生 input 元素

    U->>Input: 触发 focus() / blur()
    Input->>G: 调用 getNativeInput()
    alt WEB
        Note right of G: 在容器内查询实际 input(DOM)
        G-->>Input: 返回内部原生 input 元素
    else 非 WEB
        Note right of G: 返回 ref.current(已有引用)
        G-->>Input: 返回原生 input 引用
    end
    Input->>N: 对返回元素调用 focus() 或 blur()(可选链)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 分钟

Possibly related PRs

Suggested reviewers

  • Alex-huxiyang
  • oasis-cloud
  • xiaoyatong

Poem

我是小兔在代码林,
探索容器里的真身,
WEB 一跳寻到它,非 WEB 仍老友亲,
聚焦轻敲弹光点,输入世界又新春。 🐰✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between debe931 and ce134f6.

📒 Files selected for processing (1)
  • src/packages/input/input.taro.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/packages/input/input.taro.tsx
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions github-actions bot added 3.x Target branch 3.x action:review This PR needs more reviews (less than 2 approvals) labels Aug 20, 2025
@codecov
Copy link

codecov bot commented Aug 20, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 88.12%. Comparing base (6331fc3) to head (ce134f6).
⚠️ Report is 1 commits behind head on feat_v3.x.

Additional details and impacted files
@@              Coverage Diff              @@
##           feat_v3.x    #3341      +/-   ##
=============================================
- Coverage      88.13%   88.12%   -0.01%     
=============================================
  Files            291      291              
  Lines          19140    19140              
  Branches        2971     2970       -1     
=============================================
- Hits           16869    16868       -1     
- Misses          2266     2267       +1     
  Partials           5        5              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 6331fc3 and debe931.

📒 Files selected for processing (1)
  • src/packages/input/input.taro.tsx (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: build
  • GitHub Check: test
🔇 Additional comments (1)
src/packages/input/input.taro.tsx (1)

96-102: 用原生 input 执行 focus/blur 的方向正确

在 H5 下通过定位到 wrapper 内部的原生 input 再调用 .focus()/.blur(),可以有效规避 taro-input-core 包裹导致的聚焦失效问题。与非 WEB 环境保持兼容,不改变对外 API,取舍合理。

请在以下环境做一次冒烟验证以确保没有回归:

  • H5(WEB):ref.current.focus() 能正确聚焦到实际的原生输入框。
  • 小程序(WEAPP):ref.current.focus() 仍按旧行为可用(或不报错)。

Comment on lines 80 to 88
// 兼容H5和小程序获取原生input标签
const getNativeInput = () => {
if (Taro.getEnv() === 'WEB') {
const taroInputCoreEl = inputRef.current as HTMLElement
const inputEl = taroInputCoreEl?.querySelector?.('input')
return inputEl
}
return inputRef.current
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

明确返回类型并增强选择器,避免 TS 报错与 H5 兼容隐患

当前 getNativeInput() 在分支中返回 querySelector 的结果,TS 会推断为 Element | null。在行 96/101 对其调用 .focus()/.blur() 时,Element 类型并不包含这些方法,严格 TS 设置下会报错。此外,H5 下 Taro 自定义元素可能启用 Shadow DOM,直接 querySelector('input') 在未来版本可能失效。

建议:

  • 显式将返回类型标注为 HTMLElement | null,并将 querySelector 结果断言为 HTMLInputElement | null
  • 同时兼容 shadowRoot 下的查询,提升健壮性。
  • 与本文件后文一致,统一使用 getEnv() === ENV_TYPE.WEB,避免硬编码字符串。

可在本段内直接改为:

-  // 兼容H5和小程序获取原生input标签
-  const getNativeInput = () => {
-    if (Taro.getEnv() === 'WEB') {
-      const taroInputCoreEl = inputRef.current as HTMLElement
-      const inputEl = taroInputCoreEl?.querySelector?.('input')
-      return inputEl
-    }
-    return inputRef.current
-  }
+  // 兼容 H5 和小程序获取原生 input 标签
+  const getNativeInput = (): HTMLElement | null => {
+    if (getEnv() === ENV_TYPE.WEB) {
+      const coreEl = inputRef.current as HTMLElement | null
+      const inputEl =
+        coreEl?.querySelector?.('input') ??
+        coreEl?.shadowRoot?.querySelector?.('input')
+      return (inputEl as HTMLInputElement | null) ?? null
+    }
+    // 非 WEB:保持历史行为,直接返回 ref(其实例通常也具备 focus/blur)
+    return (inputRef.current as unknown as HTMLElement) ?? null
+  }

额外(变更范围外)的类型一致性建议:将 inputRefuseRef<HTMLInputElement>(null) 调整为更符合实际的 useRef<HTMLElement | null>(null),减少后续断言。

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// 兼容H5和小程序获取原生input标签
const getNativeInput = () => {
if (Taro.getEnv() === 'WEB') {
const taroInputCoreEl = inputRef.current as HTMLElement
const inputEl = taroInputCoreEl?.querySelector?.('input')
return inputEl
}
return inputRef.current
}
// 兼容 H5 和小程序获取原生 input 标签
const getNativeInput = (): HTMLElement | null => {
if (getEnv() === ENV_TYPE.WEB) {
const coreEl = inputRef.current as HTMLElement | null
const inputEl =
coreEl?.querySelector?.('input') ??
coreEl?.shadowRoot?.querySelector?.('input')
return (inputEl as HTMLInputElement | null) ?? null
}
// 非 WEB:保持历史行为,直接返回 ref(其实例通常也具备 focus/blur)
return (inputRef.current as unknown as HTMLElement) ?? null
}
🤖 Prompt for AI Agents
In src/packages/input/input.taro.tsx around lines 80 to 88, getNativeInput
currently returns a loosely-typed Element | null from querySelector and uses a
hard-coded 'WEB' env check; update it to explicitly return HTMLElement | null
(more specifically HTMLInputElement | null when possible), replace Taro.getEnv()
=== 'WEB' with Taro.getEnv() === ENV_TYPE.WEB, cast the querySelector result to
HTMLInputElement | null, and also check for and query inside
taroInputCoreEl.shadowRoot if present so Shadow DOM inputs are found; optionally
update the inputRef type to use useRef<HTMLElement | null>(null) (or HTMLElement
| HTMLInputElement | null) to reduce later assertions where .focus()/.blur() are
called (lines ~96/101).

@xiaoyatong xiaoyatong merged commit b8c3fd2 into jdf2e:feat_v3.x Aug 21, 2025
8 checks passed
@betterhyq betterhyq deleted the feature_hyq-FEATV3X-input-20250820-autoFocus branch August 21, 2025 02:27
xiaoyatong added a commit that referenced this pull request Aug 21, 2025
* chore(release): v3.0.18

* fix(swiper): duration属性透传 (#3337)

* feat: 修复属性透传

* feat: 直接删除duration

* fix(range): taro环境异步渲染useReady不会触发 (#3297)

* fix(range): taro环境异步渲染useReady不会触发

* refactor: 将组件中使用的useReady替换为useLayoutEffect

* chore: 升级版本号

* feat(popup): 增加上下滑动修改高度

* fix(input): 兼容h5和小程序获取原生input标签 (#3341)

* feat: inputRef获取真实input-dom

* feat: 兼容小程序和h5获取input标签

* feat: 取消?问好,出错直接抛出

* feat(Popup): 新增弹层可上下滑动 (#3340)

* feat: 支持popup 高度可以伸缩

* feat: 适配小程序

* feat: 修改文档

* fix: 默认值不需要,走样式

* feat: 增加使用的限制条件

* docs: 增加文档

* fix: 适配鸿蒙,初始值重置修改

* test: 添加单测

* fix: 增加h5 的初始值

* fix: 增加高度下限约束

* test: fix 单测

* feat(popup): 添加自定义顶部

* fix(input): taro 下只读可以点击

---------

Co-authored-by: Alex.hxy <1872591453@qq.com>
Co-authored-by: YONGQI <holyfata@qq.com>
Co-authored-by: RyanCW <75795462+Ryan-CW-Code@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

3.x Target branch 3.x action:review This PR needs more reviews (less than 2 approvals) size/S

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants