gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 21:18:02 101 4
gpt4 key购买 nike

问题是 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/

101 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com