【问题标题】:How to get asterisk* at the end of children to be red colored?如何让孩子末尾的星号*变为红色?
【发布时间】:2022-02-09 03:09:58
【问题描述】:

当 required 属性为真时,我希望孩子末尾的 * 为红色。下面的当前代码正在打印出“标签组件*”。在更改之前,我有它 {required ? `${children} * : children} 并且它可以工作,除了 * 是默认的黑色。我想做的就是把它变成红色 * 并面临困难。我究竟做错了什么? https://codesandbox.io/s/label-component-ts-zw392?file=/src/App.tsx:0-1356

import * as React from "react";

export interface ILabelProps {
  weight?: "normal" | "bold";
  htmlFor?: string;
  children?: React.ReactNode;
  testId?: string;
  required?: boolean;
}

export const Label: React.FunctionComponent<ILabelProps> = ({
  htmlFor,
  weight = "normal",
  testId,
  required = false,
  children
}: ILabelProps) => {
  const dataRef = React.useRef(null);

  const createTestId = (
    ref: HTMLElement,
    testId: string | undefined,
    testIdName: string = "data-testid"
  ) => {
    if (ref && testId) {
      ref.setAttribute(testIdName, testId);
    }
  };

  React.useEffect(() => {
    if (dataRef.current) {
      createTestId(dataRef.current, testId);
    }
  }, [dataRef, testId]);

  const requiredAsterisk = `<span color="red">*</span>`;

  return (
    <label ref={dataRef} htmlFor={htmlFor} style={{ fontWeight: weight }}>
      {required ? (
        <span>
          {children}
          {requiredAsterisk}
        </span>
      ) : (
        children
      )}
    </label>
  );
};

export const Content: React.FunctionComponent = () => {
  return (
    <div>
      <input type="text"></input>
    </div>
  );
};

export default function App() {
  return (
    <Label
      htmlFor="some-id"
      testId="testing-label"
      weight="normal"
      required={true}
    >
      Label Component
    </Label>
  );
}

【问题讨论】:

  • 你的意思是&lt;span style="color: red"&gt;*&lt;/span&gt;
  • 只将星号包裹在跨度内:return ( &lt;label ref={dataRef} htmlFor={htmlFor} style={{ fontWeight: weight }}&gt; {children} {required ? ( &lt;span style={{ color: 'red' }}&gt; {requiredAsterisk} &lt;/span&gt; ) : ( children )} &lt;/label&gt; );

标签: javascript css reactjs typescript


【解决方案1】:

您不能使用颜色道具设置颜色。如果您想将其设置为内联,则它需要位于上面提到的“样式”道具内。所以第 36 行变成了

const requiredAsterisk = <span style={{ color: "red" }}>*</span>;

【讨论】:

    猜你喜欢
    • 2021-07-12
    • 2018-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    • 1970-01-01
    • 2019-01-13
    • 2018-10-29
    相关资源
    最近更新 更多