如何在类组件中使用正向引用?

时间:2020-07-08 17:41:33

标签: javascript reactjs react-native

///如何在类组件中使用它。 //下面的代码是为功能组件编写的

function CustomTextInput(props) {
  // textInput must be declared here so the ref can refer to it
  const textInput = useRef(null);
  
  function handleClick() {
    textInput.current.focus();
  }

  return (
    <div>
      <input
        type="text"
        ref={textInput} />
      <input
        type="button"
        value="Focus the text input"
        onClick={handleClick}
      />
    </div>
  );
}

2 个答案:

答案 0 :(得分:0)

嘿,您不能在类组件中使用钩子,它们被设计为在类组件的功能组件中使用,您只能使用statethis.setState来代替,因此为您编写类版本是:

class CustomTextInput extends React.Component {
  textInput = null

  handleClick = () => {
    this.textInput.focus()
  }

  render() {
    return (
      <div>
        <input type="text" ref={(ref) => (this.textInput = ref)} />
        <input type="button" value="Focus the text input" onClick={this.handleClick} />
      </div>
    )
  }
}

class CustomTextInput extends React.Component {
  textInput = React.createRef()

  handleClick = () => {
    this.textInput.current.focus()
  }

  render() {
    return (
      <div>
        <input type="text" ref={this.textInput} />
        <input type="button" value="Focus the text input" onClick={this.handleClick} />
      </div>
    )
  }
}

带有构造函数的版本

class CustomTextInput extends React.Component {
  textInput

  constructor(props) {
    super(props)
    this.textInput = React.createRef()
  }

  handleClick = () => {
    this.textInput.current.focus()
  }

  render() {
    return (
      <div>
        <input type="text" ref={this.textInput} />
        <input type="button" value="Focus the text input" onClick={this.handleClick} />
      </div>
    )
  }
}

答案 1 :(得分:0)

在“类组件形式”中,

class CustomTextInput extends React.Component {
    textInput = React.createRef()

    handleClick = () => {
        this.textInput.current.focus()
    }

    render() {
        return (
            <div>
                <input type="text" ref={this.textInput} />
                <input
                    type="button"
                    value="Focus the text input"
                    onClick={this.handleClick}
                />
            </div>
        )
    }
}

使用构造函数,

class CustomTextInput extends React.Component {
    constructor() {
       super()
       this.textInput = React.createRef()
    }

    handleClick = () => {
        this.textInput.current.focus()
    }

    render() {
        return (
            <div>
                <input type="text" ref={this.textInput} />
                <input
                    type="button"
                    value="Focus the text input"
                    onClick={this.handleClick}
                />
            </div>
        )
    }
}