如何仅在 MUI React 中首次单击后调用无效的红色边框样式?

发布于 2025-01-19 13:38:48 字数 1369 浏览 4 评论 0原文

我一直在使用 MUI 文本字段,并且希望该字段仅在第一次单击后且输入为空白时才具有红色轮廓。所以该字段是正常的,但是一旦用户单击该字段,如果他删除或将该字段留空,轮廓应变为红色。下面的样式立即在渲染时创建红色边框。我应该改变什么?

输入图片此处描述

与此相关的几个问题:

  1. 目前,我将该字段称为必填,以便检查错误,有没有办法删除使用 required 关键字时的星号?

  2. 通过添加backgroundColor变量,看起来z-index高于字段中的文本,导致整个字段被着色并且文本被隐藏在后面。我可以做什么来修复它?

设置backgroundColor时:

在此处输入图像描述

文本字段样式:

const ValidationTextField = styled(TextFieldStyled)({
  '& input:valid + fieldset': {
    borderColor: 'green',
    borderWidth: 2,
    // backgroundColor: 'green'; // This covers the whole input so that the text input is now blocked.
  },
  '& input:invalid + fieldset': {
    borderColor: 'red',
    borderWidth: 2,
  }
});

这是使用文本字段的类:

class CompanyField extends React.Component {

  render() {
    return (
      <ValidationTextField
        id = "outlined-basic" 
        label = "Company" 
        variant = "outlined"
        fullWidth
        required

        value={this.props.value}
        onChange={this.props.handleChange}
      />
    );
  }
}

谢谢!

I have been using MUI Textfields, and would like the field to have a red outline only after the first click, and if the input is blank. So the field is normal, but once the person clicks on the field, if he deletes or leaves the field blank, the outline should become red. The styling below immediately creates a red border on render. What should I change?

enter image description here

A few more questions regarding this:

  1. Currently I have the field being called required so as to check for errors, is there a way to remove the asterisk from using the required keyword?

  2. By adding a backgroundColor variable, it seems that the z-index is higher than the text in the field, leading to the whole field being coloured and the text being hidden behind. What can I do to fix it?

When setting backgroundColor:

enter image description here

Textfield Styling:

const ValidationTextField = styled(TextFieldStyled)({
  '& input:valid + fieldset': {
    borderColor: 'green',
    borderWidth: 2,
    // backgroundColor: 'green'; // This covers the whole input so that the text input is now blocked.
  },
  '& input:invalid + fieldset': {
    borderColor: 'red',
    borderWidth: 2,
  }
});

This is the class that uses the textfield:

class CompanyField extends React.Component {

  render() {
    return (
      <ValidationTextField
        id = "outlined-basic" 
        label = "Company" 
        variant = "outlined"
        fullWidth
        required

        value={this.props.value}
        onChange={this.props.handleChange}
      />
    );
  }
}

Thank you!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蓝眼睛不忧郁 2025-01-26 13:38:48
  1. 访问Textfield的InputLabelProps,并设置为false。仍需要输入,但标签被视为不需要。 (如下所示)

  2. 不要针对输入背景,只需设置Textfield的背景色(如下所示)

以实现您的红色边框样式,创建一个状态变量以跟踪是否已单击该组件,然后使用Textfields onfocus onfocus prop,使用将状态更改为“已单击”的函数。使用该变量将样式应用于TextField:

https:/ /codesandbox.io/s/cool-varahamihira-mio1qw?file=/src/app.js

import { TextField, Box, Button } from "@mui/material";
import { useState } from "react";
import "./styles.css";

const ValidationTextField = ({ ...args }) => {
  const [firstClick, setFirstClick] = useState(true);

  return (
    <TextField
      {...args}
      onFocus={() => setFirstClick(false)}
      InputLabelProps={{
        required: false
      }}
      sx={{
        backgroundColor: "green",
        "& input:valid + fieldset": {
          borderColor: "green",
          borderWidth: 2
        },
        "& input:invalid + fieldset": {
          borderColor: firstClick ? "green" : "red",
          borderWidth: 2
        }
      }}
    />
  );
};

export default function App() {
  return (
    <div className="App">
      <Box component="form">
        <ValidationTextField
          id="outlined-basic"
          label="Company"
          variant="outlined"
          fullWidth
          required
        />
        <Button type="submit">Submit</Button>
      </Box>
    </div>
  );
}

  1. Access the InputLabelProps of textfield and set required to false. The input will still be required but the label is treated as not required. (shown in my example below)

  2. Don't target the input background, just set the backgroundColor of the textfield (shown in my example below)

To achieve your red border styling, create a state variable to track whether the component has been clicked yet, then using the textfields onFocus prop, use a function that changes the state to 'has been clicked'. Use that variable to apply styles to the textfield:

https://codesandbox.io/s/cool-varahamihira-mio1qw?file=/src/App.js

import { TextField, Box, Button } from "@mui/material";
import { useState } from "react";
import "./styles.css";

const ValidationTextField = ({ ...args }) => {
  const [firstClick, setFirstClick] = useState(true);

  return (
    <TextField
      {...args}
      onFocus={() => setFirstClick(false)}
      InputLabelProps={{
        required: false
      }}
      sx={{
        backgroundColor: "green",
        "& input:valid + fieldset": {
          borderColor: "green",
          borderWidth: 2
        },
        "& input:invalid + fieldset": {
          borderColor: firstClick ? "green" : "red",
          borderWidth: 2
        }
      }}
    />
  );
};

export default function App() {
  return (
    <div className="App">
      <Box component="form">
        <ValidationTextField
          id="outlined-basic"
          label="Company"
          variant="outlined"
          fullWidth
          required
        />
        <Button type="submit">Submit</Button>
      </Box>
    </div>
  );
}

错爱 2025-01-26 13:38:48

很抱歉在此处发布编辑,但是Stackoverflow不允许我编辑以前的帖子。但是,COOT3的方法确实适合我的问题,但是,我发现在MUI的自动完整中使用它很难:

建议的样式更改:

const ValidationDropDown = ({ ...args }) => {
    const [firstClick, setFirstClick] = useState(true);
  
    return (
      <DropDownStyled //Autocomplete Item
        {...args}
        onFocus={() => setFirstClick(false)}
        InputLabelProps={{
          required: false
        }}
        sx={{
          backgroundColor: "green",
          "& input:valid + fieldset": {
            borderColor: "green",
            borderWidth: 2
          },
          "& input:invalid + fieldset": {
            borderColor: firstClick ? "" : "red",
            borderWidth: 2
          }
        }}
      />
    );
  };

类:

class JobTypeField extends React.Component {

    render() {
        return (
            <ValidationDropDown
                id="combo-box-demo"
                options={jobType}
                required

                onChange={this.props.handleChange}
                renderInput={(params) => <TextField {...params} required label="Job Type" />}
            />
        );
    }
}

自动完整的背景确实改变了颜色,但状态没有似乎是应用的,因此边界缺乏色彩变化。

Sorry for posting an edit here, but Stackoverflow does not allow me to edit my previous post. coot3's method does work for my problem, however, I am finding it difficult to use this on MUI's autocomplete:

enter image description here

Suggested changes for styling:

const ValidationDropDown = ({ ...args }) => {
    const [firstClick, setFirstClick] = useState(true);
  
    return (
      <DropDownStyled //Autocomplete Item
        {...args}
        onFocus={() => setFirstClick(false)}
        InputLabelProps={{
          required: false
        }}
        sx={{
          backgroundColor: "green",
          "& input:valid + fieldset": {
            borderColor: "green",
            borderWidth: 2
          },
          "& input:invalid + fieldset": {
            borderColor: firstClick ? "" : "red",
            borderWidth: 2
          }
        }}
      />
    );
  };

The class:

class JobTypeField extends React.Component {

    render() {
        return (
            <ValidationDropDown
                id="combo-box-demo"
                options={jobType}
                required

                onChange={this.props.handleChange}
                renderInput={(params) => <TextField {...params} required label="Job Type" />}
            />
        );
    }
}

The autocomplete background did change colour, but the state does not appear to be applied, hence a lack of colour change in the border.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文