简体   繁体   English

当输入字段是React js中的焦点时如何更改标签颜色

[英]how to change label color when input field is focus in react js

could you please tell me how to change label color when the input field is focused in react js I am using semantic UI 你能告诉我当输入字段集中在react js中时如何更改标签颜色吗?我正在使用semantic UI

https://react.semantic-ui.com/collections/form/#types-form here is my code https://react.semantic-ui.com/collections/form/#types-form这是我的代码

<Form>
    <Form.Field>
      <label>First Name</label>
      <input placeholder="First Name" />
    </Form.Field>
    <Form.Field>
      <Checkbox label="I agree to the Terms and Conditions" />
    </Form.Field>
    <Button type="submit">Submit</Button>
  </Form>

https://codesandbox.io/s/semantic-ui-react-example-i6crv https://codesandbox.io/s/semantic-ui-react-example-i6crv

You can actually use :focus-within selector of CSS to easily apply CSS. 实际上,您可以使用CSS的:focus-within选择器轻松地应用CSS。

div:focus-within applies CSS when any element is focussed inside your div. div:focus-within任何元素都集中时应用CSS。 In your case, you can give a class to your input group — let's say input-group . 在您的情况下,您可以为input组提供一个类-假设input-group And then use .input-group:focus-within label selector to style your label. 然后.input-group:focus-within label选择器中使用.input-group:focus-within label来设置标签样式。

Check out the working code sandbox demo of your code. 查看您的代码的有效代码沙盒演示。

All I did is added the following stylesheet and it worked. 我所做的只是添加了以下样式表,并且可以正常工作。

.input-group:focus-within label {
  color: red !important;
}

You can use react hooks (useState) to change color of the label: 您可以使用react钩子 (useState)更改标签的颜色:

Working Fork - https://codesandbox.io/s/semantic-ui-react-example-fwiz4 工作叉-https: //codesandbox.io/s/semantic-ui-react-example-fwiz4

Just rewrite the component, include useState, and then use onFocus event inside the input field. 只需重写该组件,包括useState,然后在输入字段内使用onFocus事件。 Once it is focused, state hook will modify the focused state to true, which you can use to apply custom style or class. 聚焦之后,状态挂钩会将聚焦状态修改为true,您可以使用它来应用自定义样式或类。 If you have more field, just add more state params, instead of one (focused in this example). 如果您有更多字段,则只需添加更多状态参数,而不要添加一个(在此示例中重点介绍)。

import React, {useState} from "react";
import { Button, Checkbox, Form } from "semantic-ui-react";

const FormExampleForm = () => {
  const [focused, setFocused] = useState(false); // set false as initial value

  return(
    <Form>
      <Form.Field>
        <label style={{color: focused ? 'red' : ''}}>First Name</label>
        <input placeholder="First Name" onFocus={() => setFocused(true)} />
      </Form.Field>
      <Form.Field>
        <Checkbox label="I agree to the Terms and Conditions" />
      </Form.Field>
      <Button type="submit">Submit</Button>
    </Form>
  );
}

export default FormExampleForm;

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

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