我正在尝试checked
在 React 组件中查找复选框的状态。这是我的组件:
class Checkboxes extends React.Component {
constructor() {
super();
console.log('Hello world!');
this.state = {
filterEnabled: {
'desserts': true,
'juices': true,
'meats': true,
'veggies': true,
},
isApplyingFilter: false
};
}
getInitialState () {
return {
filterEnabled: {
'desserts': true,
'juices': true,
'meats': true,
'veggies': true
},
isApplyingFilter: false
};
}
render () {
const { isApplyingFilter } = this.props;
return (
<div>
<div className="row">
<div className="col-md-12">
<div className="mt-checkbox-inline">
<label className="mt-checkbox">
<input type="checkbox" name="desserts" value="desserts"
checked={this.state.filterEnabled.desserts}
/>
<span>desserts</span>
</label>
<label className="mt-checkbox">
<input type="checkbox" name="juices" value="juices"
checked={this.state.filterEnabled.juices}
/>
<span>juices</span>
</label>
<label className="mt-checkbox">
<input type="checkbox" name="meats" value="meats"
checked={this.state.filterEnabled.meats}
/>
<span>meats</span>
</label>
<label className="mt-checkbox">
<input type="checkbox" name="veggies" value="veggies"
checked={this.state.filterEnabled.veggies}
/>
<span>veggies</span>
</label>
</div>
</div>
</div>
</div>
);
}
}
我编写了以下测试场景:
it('Applying "foods" filter will display only selected food items.', () => {
// Locate the checkboxes div
var checkboxes = TestUtils.scryRenderedDOMComponentsWithTag(DOM, 'input');
// Pick the first checkbox
var cb = checkboxes[0].attributes;
// prints out "desserts"
console.log('name: ', cb['name'].value);
// prints out an empty string
console.log('checked: ', cb['checked'].value);
});
当我尝试获取 的值时cb['checked']
,它只是打印出一个空字符串''
。我期待得到true
。
获取复选框状态的正确方法是什么?