如何获取ref DOM节点“已选中”?这用于检查多个复选框,如果我可以访问被选中的refs节点为true或false,那么我可以一击触发所有复选框。另一个问题是我无法弄清楚如何通过循环获取每个复选框的值,然后在子组件内部“已检查”的每个refs Dom节点上设置一个值,我有一个完成项目:https://stackblitz.com/edit/react-qimm2x,但问题是声明性的,我的意思是简单明了,但是如果逻辑位于子组件之内,例如下面的代码,该怎么办?
import React, { Component } from 'react';
import { render } from 'react-dom';
class Items extends Component {
constructor(props){
super(props);
this.state = {
categories: [
{
id: 0,
name: "category 0",
items: [
{ name: "select all", id: Math.floor(Math.random() * 99999) }
]
},
{
id: 1,
name: "category 1",
items: [
{ name: "item 1", id: Math.floor(Math.random() * 99999) },
{ name: "item 2", id: Math.floor(Math.random() * 99999) }
]
},
{
id: 2,
name: "category 2",
items: [
{ name: "item 3", id: Math.floor(Math.random() * 99999) },
{ name: "item 4", id: Math.floor(Math.random() * 99999) }
]
},
{
id: 3,
name: "category 3",
items: [
{ name: "item 5", id: Math.floor(Math.random() * 99999) }
]
}
],
};
}
render() {
const { categories } = this.state;
return (
<div>
{categories.map(cat => {
return (
<ItemCategory
{...cat}
key={cat.id}
categories={categories}
/>
);
})}
</div>
);
}
}
class ItemCategory extends Component {
constructor(props){
super(props);
this.ItemChecked = this.ItemChecked.bind(this);
}
ItemChecked(e){
let tValue = e.target.value;
if(tValue === 'select all'){
for (const cat of this.props.categories) {
for (const item of cat.items) {
console.log(item.name)
}
}
}
}
render() {
const { items, name } = this.props;
const getItems = items.map(item => {
return item;
});
return (
<div>
<div>-{name}</div>
<ul>
{getItems.map(item => {
return (
<li key={item.id}>
<label>
<input
type="checkbox"
value={item.name}
ref={item.name}
onClick={this.ItemChecked}
/>
{item.name}
</label>
</li>
);
})}
</ul>
</div>
);
}
}
function App() {
return <Items />;
}
const rootElement = document.getElementById("root");
render(<App />, rootElement);
答案 0 :(得分:1)
您需要在onClick上使用粗箭头功能。
onClick = {e => this.ItemChecked(e)}
答案 1 :(得分:0)
const ItemChecked = (e) => {
const tValue = e.target.value;
if(tValue === 'select all'){
for (const cat of this.props.categories) {
for (const item of cat.items) {
console.log(item.name)
}
}
}
}
只需将ItemChecked
声明为箭头函数并删除构造函数上的绑定,在定义tValue
时也无需使用let。