【问题标题】:MUI Make part of a TextField bold Material UI 5MUI 使 TextField 的一部分变为粗体 Material UI 5
【发布时间】:2022-08-19 08:11:04
【问题描述】:
我有一个TextField,它有一个defaultValue,如下面的代码sn-p所示:
<TextField
autoFocus={props.autoFocus}
fullWidth
defaultValue={props.defaultValue}
value={text}
onKeyPress={handleKeyPress}
onFocus={(e) => e.target.select()}
onChange={handleChange}
/>
部分默认值用括号括起来,我希望它是粗体,而其余部分保持不变。我怎样才能做到这一点?
标签:
javascript
css
reactjs
material-ui
【解决方案1】:
您可以在运行时将 html 提供给 label 属性。 MUI TextField defaultValue 和 value 属性不允许内联 html,但 label 属性允许。此功能可能适合您的需求:
const boldTextParser = (text) => {
let i = 0;
let l = 0;
let renderables = [];
let boldtext = '';
for (i = 0; i < text.length; i += 1) {
if (text[i] === ' ') {
renderables.push(text[i]);
if (text[i + 1] === '(') {
// hold boldtext in a variable
let isBoldTextFound = false;
while (!isBoldTextFound) {
for (l = i + 2; l < text.length; l += 1) {
if (text[l] !== ')') {
boldtext = boldtext.concat(text[l]);
} else if (text[l] === ')') {
isBoldTextFound = true;
break;
}
}
}
// put bold text in rendables and update position in string
renderables.push(
<strong>
{boldtext}
</strong>,
);
// reset variables
boldtext = '';
i = l + 1;
}
}
renderables.push(text[i]);
}
return renderables;
};
现在您可以像这样在组件中使用它:
<TextField label={boldTextParser('use (label) and (not) defaultValue')} ... />