我有一个父组件。它遍历一个数组,并为数组中的每个项创建一个新的子组件。这些子组件是带有复选框和标签的div。我希望在父控件中有一个div来显示已选中复选框的数量。
最好和最简单的方法是什么?
答案 0 :(得分:0)
由于您希望计数显示在父组件上,因此您需要从该父组件跟踪它。所以我实现了count函数,并将它作为props传递给你的children组件。我们将使用Parent组件的计数状态跟踪所有子组件。请参阅下面的代码段中的App组件。
对于子组件,您只需要一个简单的复选框处理程序来控制被检查的复选框,当您这样做时,调用作为道具传入的计数函数。请参阅代码段中的Checkbox组件
class Checkbox extends React.Component {
constructor(props) {
super(props)
this.state ={
checked: false
}
}
handleCheck () {
let checked = !this.state.checked
if (checked) {
this.props.count(true)
} else {
this.props.count(false)
}
this.setState({checked})
}
render () {
return (
<div>
<label>
{this.props.name}
<input type='checkbox' checked={this.state.checked} onChange={() => this.handleCheck()}/>
</label>
</div>
)
}
}
class App extends React.Component{
constructor (props) {
super(props)
this.state = {
count: 0
}
}
count (checked) {
let { count } = this.state
if (checked) {
count ++
} else {
count --
}
console.log(count)
this.setState({count})
}
render(){
const arr = ['Checkbox1', 'Checkbox2', 'Checkbox3']
// Note: make sure to use bind on the count function since we are
// using the state from the parent component
return (
<div>
<form >
{arr.map(a => <Checkbox name={a} count={this.count.bind(this)}/>)}
</form>
{this.state.count}
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('app')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
答案 1 :(得分:-1)
const checkboxItems = ["beep", "foo", "bop", "bar"];
class App extends React.Component {
constructor(props) {
super(props);
const { checkboxItems } = this.props;
const checkedState = checkboxItems.reduce((acc, label) => {
acc[label] = false;
return acc;
}, {});
this.state = {
checkedState: checkedState
};
}
onChange = (e, label) => {
this.setState({
checkedState: {
...this.state.checkedState,
[label]: e.target.checked
}
});
};
render() {
const { checkedState } = this.state;
const { checkboxItems } = this.props;
const numChecked = Object.keys(checkedState).reduce((acc, key) => {
if (checkedState[key]) acc++
return acc
}, 0)
return (
<div>
{checkboxItems.map((label, index) => {
return (
<label key={index}>
<input
type="checkbox"
onChange={e => this.onChange(e, label)}
checked={checkedState[label]}
/>
{label}
</label>
);
})}
<div>
Number of checked inputs: {numChecked}
</div>
</div>
);
}
}
ReactDOM.render(<App checkboxItems={checkboxItems} />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>