简体   繁体   English

无法在 React 中设置 null 的属性

[英]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你有几个选择来解决这个问题

  1. Remove ref on input and set value directly by value={'Some text'} .删除输入上的 ref 并直接通过value={'Some text'}设置值。
  2. Render input and leave ref as it's but hide input by css based on condition.渲染输入并保留 ref 原样,但根据条件隐藏 css 输入。
  3. Create useEffect with listener on condition and when condition is falsy set the current.value .使用监听器创建 useEffect 条件,当条件为假时设置current.value

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

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