【发布时间】: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>
);
}
【问题讨论】:
-
你的意思是
<span style="color: red">*</span>? -
在
-
只将星号包裹在跨度内:
return ( <label ref={dataRef} htmlFor={htmlFor} style={{ fontWeight: weight }}> {children} {required ? ( <span style={{ color: 'red' }}> {requiredAsterisk} </span> ) : ( children )} </label> );
标签: javascript css reactjs typescript