简体   繁体   English

React:以 ref 作为道具有条件地渲染元素,有时 ref 会丢失

[英]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.即使两个条件(父母和孩子)都为真,参考有时会丢失并设置为 null。 How can I achieve always having the ref not equal to null?我怎样才能始终让 ref 不等于 null? I fixed everything that I could and I'm 100% sure the conditions are true我修复了我能修复的所有东西,并且我 100% 确定条件是正确的

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.停止通过 props 传递条件引用并为您的DataResultValue组件创建 bool prop isActive Each instance of this component could store ref to corresponding input/textarea and put focus in it as soon as isActive prop gets true.该组件的每个实例都可以将 ref 存储到相应的输入/文本区域,并在isActive为真后立即将焦点放在其中。

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 }}
    />
  )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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