如何传递内部参考并在HOC中使用它



假设我有输入组件和一个名为FancyInput的包装组件。

我想通过FancyInput转发内部的Input引用,也在FancyInput内部使用相同的引用,比如调用ref.focus.

编辑:

const SomeComponent = React.forwardRef((props, ref) => {
const textInputRef = useRef<TextInput>(null)
// how should I use textInputRef here, and also 
// pass the ref to the FancyInput?
return (
<View>
<FancyInput ref={textInputRef} />
</View>
)
})

您需要将组件封装在React.forwardRef.中

这是一个最小的代码片段。

const FancyInput = React.forwardRef((props, ref) => {
return <TextInput ref={ref}></TextInput>
})

假设我们在不同的组件中使用它。下面是一个例子。

const SomeComponent = (props) => {
const textInputRef = useRef<TextInput>(null)
return (
<View>
<FancyInput ref={textInputRef} />
</View>
)
}

您可以像往常一样在SomeComponent中使用ref来为FancyInput中的TextInput调用某些函数。其他组件的工作流相同。

最新更新