React中如何通过类名条件渲染控制按钮marginTop样式
解决方案
你当前的代码存在两个核心错误:
- 同一个关闭按钮元素写了两个
className属性,后面的属性会直接覆盖前面的,导致前面预设的样式类失效 - 直接对固定字符串
"big-size-file"做布尔判断,返回值永远为真,所以你原来的条件逻辑完全不生效,且你错误地将样式规则写在了className属性中,样式规则需要放到style属性或者CSS文件中。
下面提供两种可行实现方案:
方案1:纯CSS后代选择器实现(推荐,无需修改JS逻辑)
直接在你的CSS文件中追加如下规则即可,利用CSS的后代选择器自动匹配父级带big-size-file类的关闭按钮:
/* 原有规则保留 */ .big-size-file { max-width: 190px; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; display: block; } /* 新增规则 */ /* 父级带big-size-file时的关闭按钮样式 */ .big-size-file .upload-close-btn { margin-top: -17px; } /* 默认关闭按钮样式 */ .upload-close-btn { margin-top: 11px; }
然后修改React代码中关闭按钮的className,合并两个属性并新增upload-close-btn类即可:
<button type="button" onClick={handelClick} className="float-right rounded-md text-blue-500 hover:text-gray-500 focus:outline-none upload-close-btn" >
方案2:JS动态判断实现(适合父级类名需要动态切换的场景)
如果你的big-size-file类是需要根据业务逻辑动态增减的,可以将父级类名的判断逻辑抽成变量,再动态绑定到关闭按钮的样式上:
import { display } from '@mui/system'; import React from 'react'; import "../user_config/user_page.css" export default function FileUploadButton({showBtn, setShowBtn,value, isBigSize = true, ...rest}) { const handelClick = () => { setShowBtn(false); }; // 父容器类名动态生成 const parentClass = isBigSize ? "big-size-file" : ""; return ( <div style={{ position: 'relative', display: 'inline-block' ,marginTop:'10px'}} className={parentClass}> <button style={{ padding: '1px 12px', border: ' 1px solid #989797', borderRadius: '4px', color: '#727171',cursor:"pointer !important" }}> {value && showBtn ? 'Replace file' : 'Choose file'} </button> {value && showBtn?<span title={value} style={{fontSize: '9px', color: 'blue', marginLeft:'10px' }}>{value}<button type="button" onClick={handelClick} className="float-right rounded-md text-blue-500 hover:text-gray-500 focus:outline-none " style={{ marginTop: isBigSize ? '-17px' : '11px' }}> <svg xmlns="http://www.w3.org/2000/svg" className="h-3 w-3 z-100" viewBox="0 0 20 20" fill="currentColor" > <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" /> </svg> </button></span>:<span>No file chosen</span>} <input type='file' {...rest} className="fileStyle" style={{ position: 'absolute', zIndex: 2, opacity: 0, height: '100%', top: 0, bottom: 0, left: 0, right: 0 }} /> </div> ) }
你可以根据业务需求调整isBigSize的判断条件,比如通过props传值、根据上传文件大小判断等。
内容的提问来源于stack exchange,提问作者Sougata Mukherjee
相关产品推荐
相关产品推荐

