首页 文章

从重复组件传递ref

提问于
浏览
0

如何从子组件传递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 回答

  • 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;
    

    一旦使用 forwardRef 定义 Input ,就可以像平常一样使用 ref 属性 . 将:

    class App extends React.Component {
      inputRef = React.createRef();
      focusInput = () => {
        this.inputRef.current.focus();
      }
      render() {
        return <Input ref={this.inputRef} />;
      }
    }
    
  • 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 .

相关问题