javascript - 为什么 ReactJS 组件的渲染函数中需要 div ?

标签 javascript reactjs

我刚刚开始学习 Web 开发,我对 ReactJS 中的这一件事有点困惑。在我的 App 组件的渲染函数中,如果我返回没有总体 div 的 JSX:

render() {
  return (
    <h1 style={headerStyle}>Todo List</h1>
    <Todo todos={this.state.todos}/>
  );
 }

我收到错误:

./src/App.js
  Line 29:9:  Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?

  27 |      return (
  28 |         <h1 style={headerStyle}>Todo List</h1>
> 29 |         <Todo todos={this.state.todos}/>
     |         ^
  30 |      );
  31 |   }
  32 | }

但是一旦我添加了一个div:

render() {
     return (
        <div>
          <h1 style={headerStyle}>Todo List</h1>
          <Todo todos={this.state.todos}/>
        </div>
     );
  }
}

一切正常。

为什么div是必要的?或者,如果实际上没有必要,我还能做错什么?

最佳答案

在 react 中你必须有一个包装器。

您可以使用 html 标签,例如 div 或fragment

return (
        <div>
          <h1 style={headerStyle}>Todo List</h1>
          <Todo todos={this.state.todos}/>
        </div>
     );

或者片段(如果您不需要任何额外的 html 标签)

return (
        <>
          <h1 style={headerStyle}>Todo List</h1>
          <Todo todos={this.state.todos}/>
        </>
     );

 return (
        <React.Fragment>
          <h1 style={headerStyle}>Todo List</h1>
          <Todo todos={this.state.todos}/>
        </React.Fragment>
     );

供引用https://reactjs.org/docs/fragments.html

关于javascript - 为什么 ReactJS 组件的渲染函数中需要 div ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60312370/

相关文章:

javascript - 从具有特定 id 的对象的数组生成新数组

javascript - 使用 Jest-expo 测试异步存储的示例用例?

javascript - 设置开始时的状态

css - 如何使用css伪属性添加背景颜色

javascript - 从网站发布推文

javascript - 如何在验证失败时将输入边框颜色设为红色? (仅限普通 JavaScript)

javascript - 如何添加req.user来获取请求

javascript - React Hot Module Reloader 阻止摩卡测试运行

javascript - 我如何制作幻灯片,即加载开始时和悬停时停止

javascript - QuickBlox QB.chat.connect 突然给出令人困惑的身份验证错误代码 401