问题
I appreciate your help in getting me out of the mess i get into. I am very new to REACT and obviously tripping on some basic concepts.. Appreciate your kind help.
This is my app.js:
import React from "react";
import TodoItem from "./components/TodoItem";
import todosData from "./components/todosData"
function App() {
const todoComponents = todosData.map((todo) => (
<TodoItem key={todo.id} todo={todo.text} />
));
console.log(todoComponents);
return(
<div className="todo-list">
<todoComponents />,
</div>
)
}
export default App;
todoData.js:
const todosData = [{
id: "1",
text: "Take out the trash",
completed: true,
},
{
id: "2",
text: "Grocery Shopping",
completed: false,
},
{
id: "3",
text: "Clean Garage",
completed: false,
},
{
id: "4",
text: "Mow Lawn",
completed: false,
},
{
id: "5",
text: "Catch up on courses",
completed: false,
},
];
export default todosData;
Error screen with 'todoComponents' starting with lowercase 't'. Next screen will show errors when using uppercase T instead.
app.js:
import React from "react";
import TodoItem from "./components/TodoItem";
import todosData from "./components/todosData"
function App() {
const TodoComponents = todosData.map((todo) => (
<TodoItem key={todo.id} todo={todo.text} />
));
console.log(TodoComponents);
return(
<div className="todo-list">
<TodoComponents />,
</div>
)
}
export default App;
Error screen 2
Kindly ask if you need more info
回答1:
TodoComponents is not a component which you imported, you have it set as a const. Try writing it like this:
return(
<div className="todo-list">
{todoComponents}
</div>
)
You can read more about it here: https://reactjs.org/docs/conditional-rendering.html#element-variables
回答2:
The short answer: your variable, todoComponents
is an array of components. This does not make it a JSX component -- it is simply an array of JSX components.
JSX Components are either class-based, extending React.Component
or React.PureComponent
or they are a function that outputs JSX. The two examples of which are
class CustomComponent1 extends React.Component {
render() { return "I am a component"; }
}
function CustomComponent2 () {
return "I am a second component";
}
Both of these may be called, either in their own files or in other JSX files, like so.
<CustomComponent1/>
<CustomComponent2/>
However, the following could not be called as a component
const SomeArray = ['hello','there'];
// Wrong
<SomeArray/>
// Right
<div>{SomeArray}</div>
The tl;dr of this lesson is that in React, unless it's a React Component (i.e. extended from one of the previous mentioned classes) or a functional component (a function that returns JSX) then it is not a component, and cannot be used like <CustomComponent/>
.
来源:https://stackoverflow.com/questions/62522496/react-syntax-confusion-to-clarify