[英]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.