【问题标题】:Material UI TextField value with \n does not do a line break带有 \n 的 Material UI TextField 值不会换行
【发布时间】:2020-04-21 20:42:53
【问题描述】:

我正在尝试加载一个 Material-UI TextField @material-ui/core": "^4.9.11",其默认值字符串包含 \n(换行符)。

但是,我没有让 defaultValue 中的文本落在两行上。 \n 转义只是包含在该字段中。所以我想将一个包含 \n 的字符串传递给 defaultValue 并让它出现在 TextField 的两行中。

import React from "react";
import "./styles.css";
import TextField from "@material-ui/core/TextField";

export default function App() {
  return (
    <div className="App">
      <TextField multiline rows={2} defaultValue="Line1\nLine2" />
    </div>
  );
}

I've got a codesandbox of this here

【问题讨论】:

    标签: material-ui


    【解决方案1】:

    您可以为此使用变量:

    const val = "Line1\nLine2";
    return (
        <div className="App">
            <TextField multiline rows={2} defaultValue={val} />
        </div>
    );
    

    如果您使用字符串作为属性的值 - react 将看到它是最终字符串(而不是 js 字符串),这意味着您的字符串实际上是 "Line1\\nLine2"
    要解决这个问题,只需使用 js 字符串(使用变量,如上例所示)或将字符串的值作为对象传递:

    return (
        <div className="App">
            <TextField multiline rows={2} defaultValue={"Line1\nLine2} />
        </div>
    );
    

    【讨论】:

      猜你喜欢
      • 2021-10-16
      • 1970-01-01
      • 2021-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      相关资源
      最近更新 更多