【发布时间】:2020-08-31 20:51:16
【问题描述】:
尝试在用户单击按钮后禁用按钮,但来自处理函数。
我参考了这两个类似的问题: React Material UI: How to give a button a custom color when disabled? Change disable attribute in react select with material UI
我认为更改颜色会是一个很好的练习步骤,但没有奏效。当我使用 color='primary' 时,按钮是蓝色的,这就是我想要的初始状态。但是,当页面加载时,该按钮现在是灰色的(看起来已禁用,但鼠标仍然可以点击它)。
我原来的蓝色按钮:
<Button id='UploadButton' onClick={uploadButtonClicked}
variant="contained" color="primary">Upload</Button>
我修改后的按钮(尝试使用状态作为颜色):
<Button id='UploadButton' onClick={uploadButtonClicked}
disabled="{uploadButtonDisabled}"
variant="contained"
color="{uploadButtonColor}">Upload</Button>
我的状态和处理程序:
const [uploadButtonColor, setUploadButtonColor] =
React.useState('primary');
const [uploadButtonDisabled,
setUploadButtonDisabled] = React.useState('false');
const uploadButtonClicked = () => {
// will post data to a REST API here, then disable the button
setUploadButtonColor('red')
setUploadButtonDisabled('true')
}
我是否需要使用颜色模式使它看起来被禁用,或者我可以只添加禁用的单词,或者将禁用设置为 true?
这是the doc 显示禁用按钮的方式:
<Button variant="outlined" disabled>
Upload
</Button>
【问题讨论】:
-
color prop 有一些额外的大括号:
<Button id='UploadButton' onClick={uploadButtonClicked} variant="contained" color="{{UploadButtonColor}}">Upload</Button>需要改为:<Button id='UploadButton' onClick={uploadButtonClicked} variant="contained" color={UploadButtonColor}>Upload</Button>。 -
谢谢,但结果相同,我都试过了。主要问题是如何禁用。改变颜色只是实现目标的一步。
-
要禁用只需将
disabled属性设置为布尔值,就像disabled={false}一样。您可以使用您所在州的一些变量,但您仍然需要使用不带引号的单括号来插入变量。这个不行:color="{{UploadButtonColor}}"这只是字符串,React 不会插入它。它应该在单个大括号内,例如您的onClick处理程序 -
查看我上面的问题的更新。我删除了双 {{。禁用是否采用真/假?看看我试过什么。当表单加载时,为什么按钮是灰底白字?
-
我为你做了一个工作示例:codesandbox.io/s/…
标签: reactjs material-ui