react-phone-input-2组件宽高无法自定义,如何解决?
解决react-phone-input-2自定义宽高不生效的问题
我之前也碰到过一模一样的问题——react-phone-input-2的嵌套结构导致直接加样式经常被内置的material.css覆盖,折腾了好一会儿才找到靠谱的解决办法,分享给你:
1. 用CSS选择器穿透精准覆盖内部元素
这个组件的DOM结构是外层.react-phone-input-2__container包着国旗选择器和输入框.react-phone-input-2__input,直接给组件加样式只会作用在最外层容器,内部元素的样式被内置CSS优先级压制了。我们可以用嵌套选择器提升优先级:
const useStyles = makeStyles((theme) => ({ phoneWrapper: { // 外层容器的响应式宽度和间距 [theme.breakpoints.down('sm')]: { width: '95%' }, [theme.breakpoints.up('md')]: { width: '93%' }, [theme.breakpoints.up('lg')]: { width: '82%' }, marginTop: theme.spacing(2), marginRight: theme.spacing(1), marginBottom: theme.spacing(3), // 穿透到输入框,强制覆盖内置样式 '& .react-phone-input-2__input': { padding: '5px', height: '40px', width: '100%' // 让输入框占满容器宽度 }, // 可选:让国旗选择器和输入框高度对齐 '& .react-phone-input-2__flag': { height: '40px' } } }));
组件使用时保持原来的className绑定:
<PhoneInput country={'us'} value={this.props.receiverPhone} className={classes.phoneWrapper} onChange={(phone) => this.props.changePhoneNumber(phone)} />
2. 利用组件内置的containerProps和inputProps直接绑定样式
react-phone-input-2其实提供了专门给内部元素传属性的API,不用绕外层容器,直接把样式绑到目标元素上,优先级更高也更直观:
先拆分样式:
const useStyles = makeStyles((theme) => ({ phoneContainer: { [theme.breakpoints.down('sm')]: { width: '95%' }, [theme.breakpoints.up('md')]: { width: '93%' }, [theme.breakpoints.up('lg')]: { width: '82%' }, marginTop: theme.spacing(2), marginRight: theme.spacing(1), marginBottom: theme.spacing(3), }, phoneInput: { padding: '5px', height: '40px', width: '100%' } }));
然后在组件中传入这两个props:
<PhoneInput country={'us'} value={this.props.receiverPhone} containerProps={{ className: classes.phoneContainer }} inputProps={{ className: classes.phoneInput }} onChange={(phone) => this.props.changePhoneNumber(phone)} />
这个方法我个人更推荐,完全避开了样式优先级冲突的问题,代码逻辑也更清晰。
3. 极端情况:禁用内置material.css(不推荐)
如果上面两种方法都不行,你可以尝试不导入组件的material.css,自己完全重写所有样式,但这样需要处理国旗选择器、输入框、 hover/active 状态等所有细节,工作量很大,只建议作为最后手段。
内容的提问来源于stack exchange,提问作者Madhusudan chowdary
相关产品推荐
相关产品推荐

