我试图在React组件中找到复选框的checked
状态。这是我的组成部分:
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
。
获取复选框状态的正确方法是什么?
答案 0 :(得分:0)
由于您将checked设置为等于this.state.filterEnabled
,因此仅检查状态就足够了。
expect(this.state.filterEnabled.desserts).toBe(true);