在这个简单的组件中,我想选择所有的输入并监听一个变化事件,但我得到的只是一个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;
当你调用myFunc()时,没有输入。你的setLoading(true)只会在下一次渲染时影响html.在react中访问dom节点的最好方法是使用这个钩子。https:/reactjs.orgdocshooks-reference.html#useref