【问题标题】:React Materials-UI disable a button in a handlerReact Material-UI 禁用处理程序中的按钮
【发布时间】: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 有一些额外的大括号:&lt;Button id='UploadButton' onClick={uploadButtonClicked} variant="contained" color="{{UploadButtonColor}}"&gt;Upload&lt;/Button&gt; 需要改为:&lt;Button id='UploadButton' onClick={uploadButtonClicked} variant="contained" color={UploadButtonColor}&gt;Upload&lt;/Button&gt;
  • 谢谢,但结果相同,我都试过了。主要问题是如何禁用。改变颜色只是实现目标的一步。
  • 要禁用只需将disabled 属性设置为布尔值,就像disabled={false} 一样。您可以使用您所在州的一些变量,但您仍然需要使用不带引号的单括号来插入变量。这个不行:color="{{UploadButtonColor}}" 这只是字符串,React 不会插入它。它应该在单个大括号内,例如您的 onClick 处理程序
  • 查看我上面的问题的更新。我删除了双 {{。禁用是否采用真/假?看看我试过什么。当表单加载时,为什么按钮是灰底白字?
  • 我为你做了一个工作示例:codesandbox.io/s/…

标签: reactjs material-ui


【解决方案1】:

不要在属性/替换值周围加上引号 disabled={isDisabled} not disabled='{isD​​isabled}' (与颜色相同)。

你可以用这个:

import Button from "@material-ui/core/Button";

function SampleButtons(props) {
  let [isDisabled, setIsDisabled] = React.useState(false)
  return (
    <React.Fragment>
      <Button variant="contained" onClick={() => setIsDisabled(true)} disabled={isDisabled}>Button</Button>
    </React.Fragment>
  );
}

【讨论】:

  • 我想我现在明白了。为什么不将 disabled={isDisabled} 指定为:disabled="{isDisabled}"。我确实检查了控制台日志,发现了一些我以前没有检查过的错误。
  • 如果你使用 `disabled="{isDisabled}"`,你将 prop 设置为字符串。您想将isDisabled 作为变量传递
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-30
  • 2015-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多