Managing Focus 管理焦点

Managing text input focus can be a tricky task within React components. The browser focus/blur API is imperative, so setting or removing focus via declarative means purely through render() tends to feel awkward and incorrect, and it requires challenging attempts at controlling focus state.

使用 React 组件管理文本输入框是一项棘手的任务。浏览器的 focus/blur 的 API 是不可避免的,所以通过声明,使用 render() 来设置或移除焦点,这种方式会让人感到笨拙以及不正确,所以对于控制焦点状态,需要具有挑战性的尝试。

With that in mind, at Facebook we often choose to expose focus() methods on components that wrap text inputs. This breaks the declarative paradigm, but it also simplifies the work needed for engineers to successfully manage focus behavior within their apps.

带着这种想法,在 Facebook 我们经常选择在组件上暴露 focus() 方法来封装文本输入框。这打破了声明范式,但它也简化了工程师为了在其应用程序中成功地管理焦点行为,所需的工作。

The Editorcomponent follows this pattern, so there is a public focus() method available on the component. This allows you to use a ref within your higher-level component to call focus() directly on the component when needed.

Editor组件遵循这个模式,所以在组件上有一个可使用的公共 focus() 方法。这允许你在你需要时,可以在你的高级组件中使用一个 ref ,来直接使用组件上的 focus() 方法。

The event listeners within the component will observe focus changes and propagate them through onChange as expected, so state and DOM will remain correctly in sync.

组件里的事件监听器会观察 focus 的变化,并按照期望的通过 onChange 传播它们,所以 state 和 DOM 将同步的保持准确。

将容器点击转换为焦点

Your higher-level component will most likely wrap the Editorcomponent in a container of some kind, perhaps with padding to style it to match your app.

你的高级组件很可能会将 Editor组件封装在某种容器中,也许会使用 padding 来装饰它,以匹配你的应用程序。

By default, if a user clicks within this container but outside of the rendered Editorwhile attempting to focus the editor, the editor will have no awareness of the click event. It is therefore recommended that you use a click listener on your container component, and use the focus() method described above to apply focus to your editor.

默认情况下,如果一个用户在这个容器中进行了点击,但点击在了渲染的 Editor 外部,尽管他的意图是 focus 这个编辑器。这个编辑器将不知道这个单击事件。因此建议在你的容器组件中使用点击监听器,并使用 focus() 方法来描述上述 focus 的情况,再应用到你的编辑器上。

The plaintext editor example, for instance, uses this pattern.

例如,纯文本编辑器的示例,使用了此模式。

results matching ""

    No results matching ""