javascript - 如何从反应组件的地图功能中选择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;
解决方案
调用 myFunc() 时没有输入。您的 setLoading(true) 只会在下一次渲染时影响 html。在 react 中访问 dom 节点的最佳方法是使用 thise hook https://reactjs.org/docs/hooks-reference.html#useref
推荐阅读
- java - 2 个按钮 2 个 EditTexts 字符串输入 1 个 TextVew 输出
- react-native - React Native Reanimated 动画属性列表
- reactjs - 为什么指定道具的对象属性不起作用?
- react-native - RingCentral 双向通信
- java - 在加工中建造战舰。我如何将船只连接在一起并随机化船只的位置?
- python - Django模板在下拉选择中对搜索结果进行排序
- apache - 为什么我的 CORS 请求因 http 401 错误而失败
- swift - SwiftUI:是否有任何解决方案来清除 DatePicker 中的值?
- reactjs - 每次创建新用户时触发云功能
- push-notification - 说明如何订阅 FCM 频道