如何从子组件传递ref
import React, { Component } from "react";
import Text from "./Text";
import { TextInput, View, I18nManager } from "react-native";
import colors from "../styles/colors";
export default class Input extends Component {
render() {
return (
<View>
<View style={{ padding: 10 }}>
<Text>
{this.props.label}
</Text>
</View>
<TextInput
{...this.props}
placeholder={this.props.label}
/>
</View>
);
}
}
我试图专注于使用这个可重用组件的下一个输入,但它不起作用 .
<Input
label={'username'}
returnKeyType={"next"}
onSubmitEditing={() => this.refs.password.focus()}
/>
<Input label={'password'} ref={'password'} />
2 回答
你可以利用
React.forwardRef
:一旦使用
forwardRef
定义Input
,就可以像平常一样使用ref
属性 . 将:以下是如何执行此操作的示例:
CodeSandbox here .
另一种方式,使用孩子:
简答:
this.ref.current
而不是this.ref
.