What are refs in React?

前端 未结 4 688
终归单人心
终归单人心 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:18

    Refs are a way for you to get a handle back to the component you've created.

    ie.

    {this.textComponent = component}} > Here is some Text
    

    Then later in your code, you can access your text by doing:

    this.textComponent
    

    This will enable you to then invoke functions on the component in a object-oriented manner.

    I just want to point out that React/React-Native uses the declarative programming paradigm where data and "control" are managed through top-down passage of properties. Whereas in an imperative style you deal with objects and pointer and pass them around in order to invoke functions on them. Refs, in this case, is an escape hatch which allows you to get a declared component so that you can invoke functions on them in an imperative style.

    See the official React documentation for refs: https://reactjs.org/docs/refs-and-the-dom.html

提交回复
热议问题