[英]How to select DOM elements from map function in react component?
在這個簡單的組件中,我想要 select 所有輸入並監聽更改事件,但我只得到一個 null 節點列表,但我想要選定的輸入。 我如何在這個 map function 中輸入 select ?
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;
調用 myFunc() 時沒有輸入。 您的 setLoading(true) 只會在下一次渲染時影響 html。 在 react 中訪問 dom 節點的最佳方法是使用 thise hook https://reactjs.org/docs/hooks-reference.html#useref
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.