假设我有输入组件和一个名为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
调用某些函数。其他组件的工作流相同。