首页 > 解决方案 > 如何从反应组件的地图功能中选择DOM元素?

问题描述

在这个简单的组件中,我想选择所有输入并监听更改事件,但我只有一个空节点列表,但我想要选择的输入。如何在此地图功能中选择输入?

  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;

标签: javascriptreactjsdictionarydom

解决方案


调用 myFunc() 时没有输入。您的 setLoading(true) 只会在下一次渲染时影响 html。在 react 中访问 dom 节点的最佳方法是使用 thise hook https://reactjs.org/docs/hooks-reference.html#useref


推荐阅读