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

标签 reactjs react-hooks

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

  1. When one can have some loading
const Problem1 = () => {  
 const ref = useRef();

 if (loading)    
     return null;

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

}
  1. When ref is inside some condition.
const Problem2 = () => {
 const ref = useRef();

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

}

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

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

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

最佳答案

看看这是否适合你:

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

useRef()

However, useRef() is useful for more than the ref attribute. It’s handy for keeping any mutable value around similar to how you’d use instance fields in classes.

This works because useRef() creates a plain JavaScript object. The only difference between useRef() and creating a {current: ...} object yourself is that useRef will give you the same ref object on every render.

useRef 对象不会在渲染过程中改变。对于具有 current 属性的 useRef 对象,您将始终拥有相同的引用。可能会改变的是您保留在 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'));
<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"/>

关于reactjs - 当元素处于内部条件时如何使用 useRef?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58132227/

相关文章:

javascript - react 如何修复子组件中的陈旧状态

javascript - react Hook : How to read & update state in hooks without infinite loops with react-hooks/exhaustive-deps rule

javascript - react : Why is my state component not rendering?

reactjs - 在 React Router 中传递附加参数

jquery - 为 React 渲染的同一个 div 类应用不同的颜色背景

javascript - 如何将参数传递给 react 中的事件监听器

reactjs - Firebase 错误.. 错误 : Failed to make request to https://www. gstatic.com/firebasejs/releases.json

javascript - 使用 View 作为按钮 - React Native

javascript - React Hooks 和组件生命周期等效项

reactjs - 如何创建转发依赖项的 React hooks