如何在Ant Design Input.Search组件中同时禁用输入框与按钮
解决Ant Design Input.Search加载时按钮仍可点击的问题
嘿,这个小坑我之前也踩过!Ant Design的Input.Search组件默认设置loading=true时,只会禁用输入框,但内置的搜索按钮依然能被点击,确实有点反直觉。不过有两个简单靠谱的解决方案:
方案一:绑定disabled属性到loading状态(最简洁)
直接给Input.Search添加disabled属性,让它和loading状态保持一致。这样当加载中时,输入框和搜索按钮会同时被禁用,按钮也会自动变成灰色不可点击的状态,完全符合预期。
示例代码:
import { useState } from 'react'; import { Input } from 'antd'; export default function SearchBar() { const [isLoading, setIsLoading] = useState(false); const handleSearch = (searchValue) => { setIsLoading(true); // 模拟异步搜索请求 setTimeout(() => { console.log('执行搜索:', searchValue); setIsLoading(false); }, 2000); }; return ( <Input.Search placeholder="输入关键词搜索" loading={isLoading} disabled={isLoading} // 关键:将disabled与loading绑定 onSearch={handleSearch} enterButton style={{ width: 300 }} /> ); }
方案二:自定义搜索按钮,手动控制禁用状态
如果你需要自定义搜索按钮的样式、文字或者额外逻辑,可以通过enterButton插槽传入自定义按钮,然后手动给按钮设置disabled和loading属性,同时禁用输入框。
示例代码:
import { useState } from 'react'; import { Input, Button } from 'antd'; import { SearchOutlined } from '@ant-design/icons'; export default function CustomSearchBar() { const [isLoading, setIsLoading] = useState(false); const [searchValue, setSearchValue] = useState(''); const handleSearch = () => { if (!searchValue) return; setIsLoading(true); // 模拟异步请求 setTimeout(() => { console.log('自定义搜索:', searchValue); setIsLoading(false); }, 2000); }; return ( <Input.Search placeholder="输入关键词搜索" loading={isLoading} disabled={isLoading} // 禁用输入框 value={searchValue} onChange={(e) => setSearchValue(e.target.value)} enterButton={ <Button type="primary" loading={isLoading} disabled={isLoading} // 手动禁用按钮 onClick={handleSearch} > <SearchOutlined /> 开始搜索 </Button> } style={{ width: 350 }} /> ); }
两种方案都能完美解决你的问题,推荐第一种,因为代码更简洁,不需要额外的自定义逻辑。
内容的提问来源于stack exchange,提问作者timur
相关产品推荐
相关产品推荐

