如何为MUI TextField的defaultValue动态添加指定文本
解决MUI TextField根据edit状态添加"Edited"文本的问题
你需要实现的是:当edit为true时,在评论内容后追加"Edited"文本;当edit为false时,只显示原评论,不出现多余的null或false字符。
问题原因
之前的两种写法都会因为模板字符串的类型转换产生多余内容:
- 使用
${comment} ${edit ? "Edited" : null}时,null会被转为字符串"null"显示在输入框 - 使用
${comment} ${edit && "Edited"}时,edit为false时,表达式返回布尔值false,会被转为字符串"false"显示
解决方案
核心是当edit为false时返回空字符串,避免非字符串类型被转成多余字符。有两种简洁的写法:
写法一:整合空格到条件判断中
const message = `${comment}${edit ? " Edited" : ""}`;
这样当edit为true时,会在评论后加空格+"Edited";为false时,只保留原评论内容,没有多余空格。
写法二:保留原空格,条件返回空字符串
const message = `${comment} ${edit ? "Edited" : ""}`;
这种写法下,edit为false时会保留评论后的一个空格,如果你不希望有多余空格,推荐用第一种写法。
修正后的完整代码
import React, { useState } from "react"; import Box from "@mui/material/Box"; import TextField from "@mui/material/TextField"; export default function BasicTextFields() { const [edit, setEdit] = useState(true); const comment = "This is a comment from user."; // 采用第一种写法,避免多余空格 const message = `${comment}${edit ? " Edited" : ""}`; return ( <Box component="form" noValidate autoComplete="off"> <TextField id="outlined-basic" label="Outlined" variant="outlined" defaultValue={message} style={{ width: "300px" }} /> </Box> ); }
内容的提问来源于stack exchange,提问作者Happy1234
相关产品推荐
相关产品推荐

