如何通过Enzyme获取FormControlLabel子组件Switch的checked属性
如何在Enzyme浅渲染中获取FormControlLabel内部Switch组件的checked属性?
我太懂你遇到的这个问题了——用浅渲染(shallow)的时候,直接找Switch组件找不到,这其实是浅渲染的特性导致的:它只会渲染当前组件的直接子节点,而FormControlLabel里的Switch是作为control属性传进去的,属于FormControlLabel的props内容,不是它的直接子元素,所以直接find自然找不到。
给你两种可行的解决办法:
方法一:从FormControlLabel的props里直接取Switch的属性
先定位到FormControlLabel,然后通过它的props拿到传入的Switch组件,再提取checked值:
const wrapper = shallow(<MyComponent />); // 先找到FormControlLabel组件 const formControlLabel = wrapper.find('[name="formControl"]'); // 获取传入control属性的Switch的所有props const switchProps = formControlLabel.props().control.props; // 拿到checked属性值 const isChecked = switchProps.checked;
方法二:用dive()深入渲染FormControlLabel
如果你更习惯用find来定位组件,可以对找到的FormControlLabel调用dive()方法,它会深入渲染这个组件的内部结构,之后就能正常找到Switch了:
const wrapper = shallow(<MyComponent />); // 先找到FormControlLabel,dive后再找Switch const switchComponent = wrapper.find('[name="formControl"]').dive().find('[name="switch"]'); // 提取checked属性 const isChecked = switchComponent.props().checked;
这里要注意:dive()只能用于单个组件实例,所以要确保wrapper.find('[name="formControl"]')返回的是唯一的组件,不然会报错哦。
内容的提问来源于stack exchange,提问作者Bertrand P
相关产品推荐
相关产品推荐

