如何从子组件传递引用
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'} />
答案 0 :(得分:1)
这是如何执行此操作的示例:
import React from "react";
import ReactDOM from "react-dom";
class App extends React.Component {
constructor(props) {
super(props);
this.passwordRef = React.createRef();
}
handleSubmit = e => {
this.passwordRef.current.focus();
};
render() {
return (
<React.Fragment>
<input placeholder="email" />
<button onClick={this.handleSubmit}>next</button>
<hr />
<input ref={this.passwordRef} placeholder="password" />
</React.Fragment>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
CodeSandbox here。
另一种使用子级的方法:
import React from "react";
import ReactDOM from "react-dom";
class App extends React.Component {
constructor(props) {
super(props);
this.passwordRef = React.createRef();
}
render() {
return (
<React.Fragment>
<input placeholder="email" />
<Child passwordRef={this.passwordRef} />
<hr />
<input ref={this.passwordRef} placeholder="password" />
</React.Fragment>
);
}
}
const Child = ({ passwordRef }) => {
return <button onClick={() => passwordRef.current.focus()}>focus</button>;
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
简短答案:this.ref.current
,而不是this.ref
。
答案 1 :(得分:0)
您可以利用React.forwardRef
:
const Input = React.forwardRef((props, ref) => (
<View>
<View style={{ padding: 10 }}>
<Text>{this.props.label}</Text>
</View>
<TextInput {...this.props} ref={ref} placeholder={this.props.label} />
</View>
));
export default Input;
使用Input
定义了forwardRef
之后,您就可以照常使用ref
属性。会:
class App extends React.Component {
inputRef = React.createRef();
focusInput = () => {
this.inputRef.current.focus();
}
render() {
return <Input ref={this.inputRef} />;
}
}