如何在react组件的map函数中选择DOM元素?

问题描述 投票:0回答:1

在这个简单的组件中,我想选择所有的输入并监听一个变化事件,但我得到的只是一个null节点列表,但我想选择输入。

  const Component = () => {

     const [categories, setCategories] = useState([]);
     const [loading, setLoading] = useState(false);

     const myFun = () => {
        // I want to get all inputs of type cheeckbox;
        const inps = document.querySelectorAll("input[type=checkbox]");
        console.log(inps); // but I get nodeList[]
    }

    useEffect(() => {
       setCategories([...Fetched Categories from the server])
       setLoading(true);
       myFunc();
   }, []);
 return <div id="component"> 
        { loading && (categories.map((c,i)=>(
           <div className="form-group" key={i}>
             <label htmlFor={c.id}>
                <input type="checkbox" value={c.id} id={c.id}  />
                {c.title}
             </label>
           </div>
         )))
       }
     </div>
 }
export default Component;
javascript reactjs dictionary dom
1个回答
0
投票

当你调用myFunc()时,没有输入。你的setLoading(true)只会在下一次渲染时影响html.在react中访问dom节点的最好方法是使用这个钩子。https:/reactjs.orgdocshooks-reference.html#useref

© www.soinside.com 2019 - 2024. All rights reserved.