[英]Cannot set properties of null in React
I have two elements that are supposed to appear depending on whether the condition is true or false but on one of them I need to use useRef
hook but it doesn't work.我有两个元素应该根据条件是真还是假出现,但在其中一个元素上我需要使用useRef
钩子,但它不起作用。 Even though the element sometimes renders first, I still get the error Cannot set properties of null
.即使元素有时首先呈现,我仍然收到错误Cannot set properties of null
。 I need to edit the second element's value when it renders with its reference but the code crashes so I can't do anything.当第二个元素使用其引用呈现时,我需要编辑它的值,但代码崩溃了,所以我什么也做不了。 Code looks like this:代码如下所示:
inputRef.current.value="Some text"
{condition ? <SomeOtherComponent /> : <input type="text" ref={inputRef} />}
You have few options to fix that你有几个选择来解决这个问题
value={'Some text'}
.删除输入上的 ref 并直接通过value={'Some text'}
设置值。current.value
.使用监听器创建 useEffect 条件,当条件为假时设置current.value
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.