简体   繁体   中英

Learning React: how to useRef in custom component?

I'm learning React and I don't think I understand the concept of useRef properly. Basically, I want to include some tags in tagify input field when a user clicks on a chip that is rendered outside the input box.

My idea is to do something like this ( App.js ):

import Chip from '@material-ui/core/Chip';
import Tagify from "./Tagify"

...

class App extends React.Component {

...

   const { error, isLoaded, quote, tags } = this.state; //tags comes from the server

   var tagify = <Tagify tags={tags} />
   const addTagOnChipClick = (tag) => {
       tagify.addTag(tag)
     };

   const chips = tags.map(tag => (
       <span key={tag.name} className="chips">
         <Chip
           label={tag.name}
           variant="outlined"
           onClick={addTagOnChipClick(tag)}
           clickable
         />
       </span>
     ))

...

}

The tagify documentation says that

To gain full access to Tagify's (instance) inner methods, A custom ref can be used: <Tags tagifyRef={tagifyRef} ... />

My attempt to gain access to these inner methods was to use useRef ( Tagify.js ):

import Tags from '@yaireo/tagify/dist/react.tagify'

import '@yaireo/tagify/dist/tagify.css'

export default function Tagify(tags) {
   const tagifyRef = useRef()

   return (
       <Tags
           tagifyRef={tagifyRef}
           placeholder='Filter by tags...'
           whitelist={tags.tags}
       />
    )
}

However, tagifyRef.current is undefined . What I'm doing wrong? There's another way to access the inner methods?

Thank you very much!

When are you accessing the ref? Make sure you access the ref only after the component has mounted ie in a useEffect:

import Tags from '@yaireo/tagify/dist/react.tagify'

import '@yaireo/tagify/dist/tagify.css'

export default function Tagify(tags) {
   const tagifyRef = useRef()

  React.useEffect(() => {
     console.log(tagifyRef.current)
  }, [])

   return (
       <Tags
           tagifyRef={tagifyRef}
           placeholder='Filter by tags...'
           whitelist={tags.tags}
       />
    )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM