我刚刚开始学习 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>
);
关于javascript - 为什么 ReactJS 组件的渲染函数中需要 div ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60312370/