简体   繁体   中英

React: conditionally render element with ref as a prop, sometimes ref is lost

Here are my components:

// parent component
const activeTextareaFieldRef = useRef(null);

return (
  <GroupField textareaRef={activeField.id === id ? activeTextareaFieldRef : null} />
)

// group field component
<>
  <DataResultValue ref={item.name === activeField.subFieldName ? textareaRef : null} />
</>

Even if both conditions (in parent and child) are true, the ref is sometimes lost and is set to null. How can I achieve always having the ref not equal to null? I fixed everything that I could and I'm 100% sure the conditions are true

If your task is just focusing particular field then maybe you will find this solution useful.

Stop passing conditional refs via props and create bool prop isActive for your DataResultValue component. Each instance of this component could store ref to corresponding input/textarea and put focus in it as soon as isActive prop gets true.

For example:

const DataResultValue = ({ value, isActive }) => {
  const inputRef = React.useRef()
  
  React.useEffect(() => {
    if (isActive) {
      inputRef.current.focus()    
    }
  }, [isActive])
  
  return (
    <input
      ref={inputRef}
      defaultValue={value}
      style={{ color: isActive ? 'red' : null }}
    />
  )
}

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