【问题标题】:How to render a JSX that is inside a variable如何渲染变量内的 JSX
【发布时间】:2018-01-25 04:49:48
【问题描述】:

我正在执行 if/else 语句来设置名为“signupMessage”的 JSX 元素的内容。我稍后会渲染“signupMessage”的内容。

render() {
  let signupMessage;
  if (this.state.signUpForNewsletter === true) {
    signupMessage = <h1>Thank you</h1>;
  } else if (this.state.signUpForNewsletter === false) {
    signupMessage = <h1>Be the first</h1> + <h1>to see the latest!</h1>;
  }
  return(
  <section className="sign-up">
    {signupMessage}
  </section>
)}

在“else if”块中,我需要两个 h1 标签,以便根据规范准确控制一行上出现的单词,即使在不同的设备上也是如此。

现在,这输出为“[object Object][object Object]”。如何让 JSX 呈现为 h1 标签??

【问题讨论】:

    标签: javascript html reactjs jsx


    【解决方案1】:

    在您的代码中,这一行:

    <h1>Be the first</h1> + <h1>to see the latest!</h1>
    

    被转译为:

    React.createElement("h1", null, "Be the first") +
    React.createElement("h1", null, "to see the latest!");
    

    React.createElement返回一个对象,而JS中的object + object结果:

    "[object Object][object Object]"
    

    这就是您看到该输出的原因。


    如何解决这个问题

    将两个&lt;h1&gt;s 包裹在&lt;div&gt; 中:

    signupMessage = <div><h1>Be the first</h1><h1>to see the latest!</h1></div>;
    

    【讨论】:

    • 我在回答 5 分钟后写的那种,但你得到了我对 React.createElement 部分的投票 :)
    • @Dekel,我也赞成你的回答:)。我觉得给出额外的解释会增加足够的讨论以保证另一个答案,因此是这样。 (感谢您的支持。)
    • 在我看来,React 在变量中处理 JSX 的方式似乎不同,如果将这些 html 放在
      标记中,它会像我想的那样工作得很好。
    【解决方案2】:

    尝试在您需要消息的第二位位于另一行的地方添加一个中断,并且只返回一个 h1 标记:

    render() {
      let signupMessage;
      if (this.state.signUpForNewsletter === true) {
        signupMessage = <h1>Thank you</h1>;
      } else if (this.state.signUpForNewsletter === false) {
        signupMessage = <h1>Be the first<br />to see the latest!</h1>;
      }
      return(
      <section className="sign-up">
        {signupMessage}
      </section>
    )}
    

    【讨论】:

      【解决方案3】:

      JSX 元素必须有一个容器:

      render() {
        let signupMessage;
        if (this.state.signUpForNewsletter === true) {
          signupMessage = <h1>Thank you</h1>;
        } else if (this.state.signUpForNewsletter === false) {
          signupMessage = <div><h1>Be the first</h1><h1>to see the latest!</h1></div>;
        }
        return(
        <section className="sign-up">
          {signupMessage}
        </section>
      )}
      

      而不是尝试连接“字符串”(如果它是 html,你会这样做) - 将它们包装在一个新容器中并呈现该容器。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-02
        • 2017-10-12
        • 2020-06-28
        • 2022-08-18
        • 2019-06-03
        • 1970-01-01
        • 1970-01-01
        • 2020-05-27
        相关资源
        最近更新 更多