reactjs - 为什么在 React 中返回时需要额外的包装器?

标签 reactjs

所以,我开始学习React,我遇到了这段代码,我真的很困惑。

以下代码给出错误:

function getNum() {
  return Math.floor(Math.random() * 10 + 1);
}

class Number extends React.Component {
  render() {
    const num = getNum();
    let msg;
    if (num % 2 == 0) {
      msg = (
        <div>
          <h2>Even Number</h2>
          <p>The number is: {num}</p>
        </div>
      );
    } else {
      msg = (
        <div>
          <h2>Odd Number</h2>
          <p>The number is: {num}</p>
        </div>
      );
    }
    // THIS IS WHAT CAUSES ERROR
    return {msg};
  }
}

ReactDOM.render(<Number />, document.getElementById("root"));

但是如果我将 return 包裹在像这样的 div 中 <div>{msg}</div>错误消失。我很困惑为什么会这样?因为 msg 变量有一个父级,所以返回值也有一个父级,所以为什么我需要那个额外的 div 容器?

最佳答案

通过这样的写法,它被解释为一个带有名为 msg 的单个键的对象。无需包装 JSX 标签,您只需编写:

return msg;

当您需要运行 JavaScript block 或引用变量时,应在 JSX 标记内使用方括号。

关于reactjs - 为什么在 React 中返回时需要额外的包装器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64623706/

相关文章:

reactjs - 如何防止用户在 react 中多次点击登录表单的提交按钮错误?

parse-platform - react native 并解析,登录和 cmd+R 后当前用户为空

reactjs - 我正在尝试设置 jsconfig.json 但出现此错误

reactjs - React-i18next 每个组件的翻译

javascript - 进度条的 Aria 标签 - 我需要它们来显示部分标题吗

android - 如何在 Linux 上的 React Native 中使用 gradle 解决此错误?

css - 如何改变Ant-Design 'Select'组件的样式?

javascript - 由于上下文中未使用的属性,组件重新呈现

reactjs - MUI TextField 不接受模式

javascript - 设置状态(...): This usually means you called set state() on an unmounted component