使用React和Material UI禁用自动填充表单

ogk*_*ogk 6 javascript css reactjs material-design material-ui

我正在尝试学习React和Material UI.

我正在创建一个Web表单,到目前为止一切都很好,除非页面加载时,chrome自动用以前存储的数据填充文本字段,背景变为黄色.我该如何保持白色?

我知道在普通的CSS中我会包含这段代码:

input:-webkit-autofill {
    -webkit-box-shadow: 0 0 0 1000px white inset;
}
Run Code Online (Sandbox Code Playgroud)

然而,考虑到这一点,我不一定有样式表,这就是一个问题.

我到目前为止:

const MyAwesomeReactComponent = React.createClass({
const containerStyle = 
    {
      /* input:-webkit-autofill {
    -webkit-box-shadow: 0 0 0 1000px white inset;
          } */
    };
 return (
      <div style={containerStyle}>
           <form action="/login" method="post" autocomplete ="off">
              <div>
                  <TextField hintText="Email Field" floatingLabelText="Email"  underlineFocusStyle={{borderColor: Colors.amber900}} />
              </div>
              <div>
                  <TextField hintText="Password Field" floatingLabelText="Password" type="password" />
              </div>
              <div>
                  <RaisedButton label="Submit" primary={true}/>
              </div>
          </form>
});
module.exports = MyAwesomeReactComponent;
Run Code Online (Sandbox Code Playgroud)

我在解析input-webkit-autofill代码时遇到语法错误.

Dax*_*hen 5

如果你想在javascript中编写css,你必须将dashed-key-words转换为camelCaseKeys

例如:

  • background-color => backgroundColor
  • border-radius => borderRadius

但供应商前缀以大写字母开头(除外ms)

  • -webkit-box-shadow=> WebkitBoxShadow(大写W)
  • -ms-transition=> msTransition('ms'是唯一的小写供应商前缀)

有关更多详细信息,请参阅react #inline-styles部分

所以在你的例子中:

const containerStyle = {
  WebkitBoxShadow: '0 0 0 1000px white inset'
};
Run Code Online (Sandbox Code Playgroud)

现在,因为内联样式直接附加在标签上而不是使用选择器,我们必须将此样式放在<input>标签本身而不是容器上.

要覆盖<input>样式<TextField>,请使用此处记录inputStyle道具

编辑: 但这样做,你将丢失提示文本,因为它将被盒阴影覆盖.添加z-index提示文本可以解决这个问题!

所以最后你的例子将是这样的:

const hideAutoFillColorStyle = {
  WebkitBoxShadow: '0 0 0 1000px white inset'
};
const hintStyle = { zIndex: '1' };

<div>
  <TextField
    hintText="Email Field"
    floatingLabelText="Email"
    underlineFocusStyle={{borderColor: Colors.amber900}}
    inputStyle={hideAutoFillColorStyle}
    hintStyle={hintStyle} />
</div>
<div>
  <TextField
    hintText="Password Field"
    floatingLabelText="Password"
    type="password"
    inputStyle={hideAutoFillColorStyle}
    hintStyle={hintStyle} />
</div>
Run Code Online (Sandbox Code Playgroud)

注意:反应内联样式有一些限制,例如@media查询.要解决这个问题,您可以使用<style>标签:有关更多示例,请参阅此文章!

顺便说一句,你可以使用一些autoprefixer(如post-css)为你做前缀工作.


haz*_*ous 1

您可以添加带有输入伪样式的 CSS 文件,并为容器 div 指定 className。您应该将该文件包含在 SPA html 中。

例如 CSS 文件...

.formcontainer input:-webkit-autofill { -webkit-box-shadow: 0 0 0 1000px white inset; }
Run Code Online (Sandbox Code Playgroud)

然后在你的渲染代码中 -

<div className="formcontainer"><form ...>
Run Code Online (Sandbox Code Playgroud)

并且不要忘记将 CSS 文件包含在您的 html 页面中!

对于错误的缩进表示歉意,我正在使用 SO 应用程序。