简体   繁体   English

更改所有出现的字符的颜色 javascript/reactjs

[英]Change color of all occurrences of a character javascript/reactjs

I am working with reactjs have a form with multiple input fields and some of them have labels with an asterisk to indicate that the field is mandatory.我正在使用 reactjs 有一个包含多个输入字段的表单,其中一些带有带有星号的标签,以指示该字段是强制性的。 I want to change the color of all the asterisks(*) to red for better visibility to the user.我想将所有星号 (*) 的颜色更改为红色,以便更好地向用户显示。 How can I change the color of all occurrences of the asterisk in my form to red at once?如何将表单中所有出现的星号的颜色一次更改为红色?

PS : I don't want to put the asterisk in a span or a div. PS:我不想将星号放在跨度或 div 中。 Rather I would like to write code so that every asterisk in the form gets the color red with a single piece of global code.相反,我想编写代码,以便表单中的每个星号都通过一段全局代码获得红色。

You should wrap asterisks in span element and assign some class.您应该在 span 元素中包装星号并分配一些类。 So you can give color to that class element in your css file.因此,您可以在 css 文件中为该类元素赋予颜色。

Like this像这样

<span class="required">*</span>

And in CSS在 CSS 中

.required
{
   color:red;
}

It's rather unclear what exactly you're trying to accomplish without having any code to reference.在没有任何代码可供参考的情况下,您究竟要完成什么还不清楚。 But I'm assuming what you're actually trying to highlight the asterisks (*) belonging to labels for fields that are empty during form-submission.但我假设您实际上试图突出显示属于表单提交期间空字段标签的星号 (*)。

Try something like this: https://codesandbox.io/s/holy-leftpad-hw1oe尝试这样的事情: https : //codesandbox.io/s/holy-leftpad-hw1oe

class App extends React.Component {
  state = {
    name: "",
    password: "",
    errors: false
  };

  handleOnChange = event => {
    this.setState({
      [event.target.name]: event.target.value
    });
  };

  handleOnSubmit = event => {
    event.preventDefault();
    const { name, password } = this.state;
    if (name.length === 0 || password.length === 0) {
      this.setState({
        errors: true
      });
    } else {
      this.setState({
        errors: false
      });
    }
  };

  render() {
    const { name, password, errors } = this.state;
    return (
      <form onSubmit={this.handleOnSubmit}>
        <label>
          Name{" "}
          <span
            className={errors && name.length === 0 ? "error-label" : "label"}
          >
            (*)
          </span>
        </label>
        <input name="name" onChange={this.handleOnChange} />
        <label>
          Password
          <span
            className={
              errors && password.length === 0 ? "error-label" : "label"
            }
          >
            (*)
          </span>
        </label>
        <input name="password" onChange={this.handleOnChange} />
        <button type="submit">Submit</button>
      </form>
    );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM