What are refs in React?

前端 未结 4 683
终归单人心
终归单人心 2021-02-09 05:38

I\'m having trouble understanding what refs are in React. I understand that it\'s a callback function and you put it in the render function, but beyond that I can\'t understand

4条回答
  •  孤城傲影
    2021-02-09 06:10

    Refs are an escape hatch which allows you to get direct access to a DOM element or an instance of a component. In order to use them, you add a ref attribute to your component whose value is a callback function which will receive the underlying DOM element or the mounted instance of the component as its first argument.

    class UnControlledForm extends Component {
      handleSubmit = () => {
        console.log("Input Value: ", this.input.value)
      }
      render () {
        return (
          
    this.input = input} />
    ) } }

    refs can also be used with functional components by leveraging closures in JavaScript.

    function CustomForm ({handleSubmit}) {
      let inputElement
      return (
        
    handleSubmit(inputElement.value)}> inputElement = input} />
    ) }

    ("Closures" just being a fancy way of saying referencing a variable that's declared outside the function - in this case, inputElement - within your function, in this case ref={(input) => inputElement = input}.)

提交回复
热议问题