简体   繁体   English

MUI 使 TextField 的一部分变为粗体 Material UI 5

[英]MUI Make part of a TextField bold Material UI 5

I have a TextField that has a defaultValue as shown in below code snippet:我有一个具有defaultValueTextField ,如下面的代码片段所示:

  <TextField
      autoFocus={props.autoFocus}
      fullWidth
      defaultValue={props.defaultValue}
      value={text}
      onKeyPress={handleKeyPress}
      onFocus={(e) => e.target.select()}
      onChange={handleChange}
  />

Part of the default value is wrapped in parentheses, I would like this to be bold while the rest stays the same.部分默认值用括号括起来,我希望它是粗体,而 rest 保持不变。 How can I achieve this?我怎样才能做到这一点?

You could provide html to the label attribute at runtime.您可以在运行时将 html 提供给 label 属性。 The MUI TextField defaultValue and value attributes don't allow for inline html, but the label attribute does. MUI TextField defaultValue 和 value 属性不允许内联 html,但 label 属性允许。 This function might suite your needs:这个 function 可能适合您的需求:

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;
};

Now you can use it in your component like this:现在您可以像这样在组件中使用它:

<TextField label={boldTextParser('use (label) and (not) defaultValue')} ... />

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

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