【问题标题】:React: How to display JSON key value pairs with line breaks?React:如何显示带有换行符的 JSON 键值对?
【发布时间】:2019-06-19 04:06:13
【问题描述】:

我有以下组件,其中包含一个名为 onClickBtn() 的函数,该函数包含另一个名为 textBuilder() 的函数,该函数迭代了一个 JSON 对象,其中填充了来自表单的数据。单击提交按钮时,我正在使用电子邮件服务以编程方式发送电子邮件。唯一的问题是我的电子邮件的 Body 值最终在电子邮件中看起来像这样:

name: Dean age: 26 email: dean@aol.com styles: Color locations: Right Leg specificLocation: fasdfasdfa description: fdghjdghj budgets: $1000-$1500 days: Wednesday months: June  

代替:

name: Dean 

age: 26 

email: dean@aol.com 

styles: Color 

locations: Right Leg 

specificLocation: fasdfasdfa 

description: fdghjdghj 

budgets: $1000-$1500 

days: Wednesday 

months: June  

下面是我的组件。谁能告诉我我做错了什么?

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';

const useStyles = makeStyles(theme => ({
  button: {  margin: theme.spacing(1), },
  input: { display: 'none', },
}));

export default function ContainedButtons(props) {
  const classes = useStyles();  

  const onClickBtn = () => {

    const textBuilder = () => {
      var doc = "";
      for (const key in props.values) {
       doc += key + ": " + props.values[key] + "\n";      
      }
      return doc;
    } 

    window.Email.send({
      Host : "smtp.elasticemail.com",
      Username : "dfmmalaw@gmail.com",
      Password : "d2296492-2689-49f7-ae3d-584f1507d23a",
      To : 'dfmmalaw@gmail.com',
      From : "dfmmalaw@gmail.com",
      Subject : "This is the subject",
      Body : textBuilder()
  }).then(
    message => alert(message)
  );
  };

    return (
      <div>
        <Button variant="contained" color="primary" className={classes.button} disabled = {!props.isEnabled} type="submit" onClick={onClickBtn}>
          Submit
        </Button>
      </div>
    );
}

【问题讨论】:

  • 这可能是因为您的电子邮件客户端将内容呈现为 HTML。所以换行符只是转换为空格。尝试使用 break 元素,如下所示:doc += key + ": " + props.values[key] + "&lt;br/&gt;";
  • 嗯...好电话...让我试试。
  • 太棒了!像魅力一样工作。您能否将您的评论转换为答案,以便我选择它?

标签: javascript json reactjs


【解决方案1】:

这是因为您的电子邮件客户端将内容呈现为 HTML。所以换行符只是转换为空格。尝试使用 break 元素,如下所示:

doc += key + ": " + props.values[key] + "<br/>";

【讨论】:

    猜你喜欢
    • 2021-03-03
    • 2021-09-26
    • 1970-01-01
    • 2015-04-05
    • 2022-01-09
    • 2021-01-06
    • 1970-01-01
    • 2019-07-23
    • 2016-01-17
    相关资源
    最近更新 更多