3 回答

TA貢獻(xiàn)1817條經(jīng)驗(yàn) 獲得超14個(gè)贊
您的 Checkbox 處理程序應(yīng)該位于構(gòu)造函數(shù)之外。
如下所示:
constructor(props) {
super(props);
this.state = {
allCheckboxes: true
};
}
handleAllCheckboxes = (e) => {
const allCheckboxesChecked = e.target.checked
let checkboxes = document.getElementsByName('checkbox')
this.setState({
allCheckboxes: allCheckboxesChecked
})
console.log(allCheckboxesChecked)
}
你寫(xiě)了checked={this.handleAllCheckboxes ?true : false}看起來(lái)是錯(cuò)誤的。因?yàn)?**this.handleAllCheckboxes 已經(jīng)定義,因此它將始終返回 true。(因?yàn)楹瘮?shù)始終可用。)**。其次,handleAllCheckboxes 也沒(méi)有返回任何真/假。

TA貢獻(xiàn)1785條經(jīng)驗(yàn) 獲得超8個(gè)贊
有一個(gè)包grouped-checkboxes可以解決這個(gè)問(wèn)題。
您可以簡(jiǎn)單地將復(fù)選框包裝在 CheckboxGroup 中并添加 AllChecker。
import React from 'react';
import {
CheckboxGroup,
AllCheckerCheckbox,
Checkbox
} from "@createnl/grouped-checkboxes";
const App = (props) => {
const { products } = props
return (
<CheckboxGroup onChange={console.log}>
<label>
<AllCheckerCheckbox />
Select all
</label>
{options.map(option => (
<label>
<Checkbox id={option.id} />
{option.label}
</label>
))}
</CheckboxGroup>
)
}
更多示例參見(jiàn)https://codesandbox.io/s/grouped-checkboxes-v5sww

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超13個(gè)贊
您需要保持復(fù)選框狀態(tài),單擊全選時(shí)將其狀態(tài)更改為 true,反之亦然。
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<div id="root"></div>
<script type="text/babel">
class App extends React.Component {
constructor() {
super();
this.state = {
checkBoxes: {
vehicle1: false,
vehicle2: false,
vehicle3: false,
}
};
}
handleCheckBoxes = (checkBox, checkAll = false) => {
if (checkAll) {
const checkBoxes = { ...this.state.checkBoxes };
Object.keys(checkBoxes).forEach((key) => {
checkBoxes[key] = checkBox.target.checked;
});
this.setState({
checkBoxes: checkBoxes
})
return;
}
const { checked, name } = checkBox.target;
this.setState(
prevState => {
return {
checkBoxes: { ...prevState.checkBoxes, [name]: checked }
};
},
() => console.log(this.state)
);
// console.log(checkBox.target.checked);
};
render() {
return (
<div>
<label>
<input
type="checkbox"
onChange={e => this.handleCheckBoxes(e, true)}
name="vehicle1"
value="Bike"
/>
Select All
</label>
<br />
<input
type="checkbox"
onChange={this.handleCheckBoxes}
name="vehicle1"
value="Bike"
checked={this.state.checkBoxes["vehicle1"]}
/>
<input
type="checkbox"
onChange={this.handleCheckBoxes}
name="vehicle2"
value="Car"
checked={this.state.checkBoxes["vehicle2"]}
/>
<input
type="checkbox"
onChange={this.handleCheckBoxes}
name="vehicle3"
value="Boat"
checked={this.state.checkBoxes["vehicle3"]}
/>
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
</script>
添加回答
舉報(bào)