Skip to main content

直接操纵

有时需要直接对组件进行更改,而不使用状态/属性来触发整个子树的重新渲染。例如,在浏览器中使用 React 时,有时需要直接修改 DOM 节点,移动应用中的视图也是如此。setNativeProps 是 React Native 相当于直接在 DOM 节点上设置属性。

¥It is sometimes necessary to make changes directly to a component without using state/props to trigger a re-render of the entire subtree. When using React in the browser for example, you sometimes need to directly modify a DOM node, and the same is true for views in mobile apps. setNativeProps is the React Native equivalent to setting properties directly on a DOM node.

提醒

当频繁重新渲染造成性能瓶颈时,请使用 setNativeProps

¥Use setNativeProps when frequent re-rendering creates a performance bottleneck!

直接操作不会是你经常使用的工具。你通常只会使用它来创建连续动画,以避免渲染组件层次结构和协调许多视图的开销。setNativeProps 是命令式的,它将状态存储在原生层(DOM、UIView 等)中,而不是存储在 React 组件中,这使得你的代码更难以推断。

¥Direct manipulation will not be a tool that you reach for frequently. You will typically only be using it for creating continuous animations to avoid the overhead of rendering the component hierarchy and reconciling many views. setNativeProps is imperative and stores state in the native layer (DOM, UIView, etc.) and not within your React components, which makes your code more difficult to reason about.

在使用之前,请尝试用 setStateshouldComponentUpdate 解决你的问题。

¥Before you use it, try to solve your problem with setState and shouldComponentUpdate.

setNativeProps 编辑 TextInput 值

¥setNativeProps to edit TextInput value

setNativeProps 的另一个非常常见的用例是编辑 TextInput 的值。当 bufferDelay 较低且用户键入速度非常快时,TextInput 的 controlled 属性有时会丢失字符。一些开发者更喜欢完全跳过此属性,而是在必要时使用 setNativeProps 直接操作 TextInput 值。

¥Another very common use case of setNativeProps is to edit the value of the TextInput. The controlled prop of TextInput can sometimes drop characters when the bufferDelay is low and the user types very quickly. Some developers prefer to skip this prop entirely and instead use setNativeProps to directly manipulate the TextInput value when necessary.

例如,以下代码演示了点击按钮时编辑输入:

¥For example, the following code demonstrates editing the input when you tap a button:

你可以使用 clear 方法来清除 TextInput,后者使用相同的方法清除当前输入的文本。

¥You can use the clear method to clear the TextInput which clears the current input text using the same approach.

避免与渲染函数发生冲突

¥Avoiding conflicts with the render function

如果你更新也由渲染函数管理的属性,则可能会遇到一些不可预测且令人困惑的错误,因为每当组件重新渲染且该属性发生更改时,之前从 setNativeProps 设置的任何值都将被完全忽略和覆盖。

¥If you update a property that is also managed by the render function, you might end up with some unpredictable and confusing bugs because anytime the component re-renders and that property changes, whatever value was previously set from setNativeProps will be completely ignored and overridden.