当元素处于条件内时如何使用useRef?

Ser*_*tov 3 reactjs react-hooks

问题是 useRef 在第一次渲染期间被触发。可能有问题的两个例子。

  1. 当一个人可以有一些负载
const Problem1 = () => {  
 const ref = useRef();

 if (loading)    
     return null;

 return <input ref={ref} value={} />;

}
Run Code Online (Sandbox Code Playgroud)
  1. 当 ref 在某个条件内时。
const Problem2 = () => {
 const ref = useRef();

 return user ? <input ref={ref} value={user.name} /> : <Exit >;

}
Run Code Online (Sandbox Code Playgroud)

沙盒示例 https://codesandbox.io/s/nifty-feynman-z68k0

在第二种情况下,我至少可以在开头显示元素 display: none。但是如何解决第一个问题我不知道。

在这些情况下,最佳做法是什么?

cbd*_*per 5

看看这是否适合你:

来自 React DOCS:https : //reactjs.org/docs/hooks-reference.html#useref

使用引用()

但是, useRef() 不仅对 ref 属性有用。保持任何可变值类似于在类中使用实例字段的方式,这很方便。

这是有效的,因为 useRef() 创建了一个普通的 JavaScript 对象。useRef() 和自己创建一个 {current: ...} 对象之间的唯一区别是 useRef 将在每次渲染时为您提供相同的 ref 对象。

useRef对象不会改变整个渲染。对于useRef具有current属性的对象,您将始终拥有相同的引用。可能会改变的是您保留在该current属性中的内容。

function App() {

  const input1_ref = React.useRef(null);
  const input2_ref = React.useRef(null);
  const [showInput2, setShowInput2] = React.useState(false);
  
  React.useEffect(()=>{
    input1_ref.current ?
      console.log('Input1 has been mounted...')
    : console.log('Input1 has NOT been mounted...');
    input2_ref.current ?
      console.log('Input2 has been mounted...')
    : console.log('Input2 has NOT been mounted...');
  });
  

  return(
    <React.Fragment>
      <div>Input 1</div>
      <input type='text' ref={input1_ref}/>
      {showInput2 &&
        <React.Fragment>
          <div>Input 2</div>
          <input type='text' ref={input2_ref}/>
        </React.Fragment>
      }
      <div>
        <button onClick={()=>setShowInput2((prevState)=>!prevState)}>Click</button>
      </div>
    </React.Fragment>
  );
}

ReactDOM.render(<App/>, document.getElementById('root'));
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>
Run Code Online (Sandbox Code Playgroud)