簡體   English   中英

React - 語法混淆澄清

[英]React - syntax confusion to clarify

感謝您幫助我擺脫困境。 我對 REACT 很陌生,顯然在一些基本概念上絆倒了。感謝您的幫助。

這是我的 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;

“todoComponents”以小寫“t”開頭的錯誤屏幕。 下一個屏幕將在使用大寫 T 時顯示錯誤。

參考1

應用程序.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;

錯誤畫面 2

參考2

請詢問您是否需要更多信息

TodoComponents 不是您導入的組件,您將其設置為 const。 試着這樣寫:

return(
    <div className="todo-list">
      
        {todoComponents}
      
    </div>
)

你可以在這里閱讀更多關於它的信息: https://reactjs.org/docs/conditional-rendering.html#element-variables

簡短的回答:您的變量todoComponents是一個組件數組。 這並不能使它成為一個 JSX 組件——它只是一個 JSX 組件數組。

JSX 組件要么是基於類的,擴展React.ComponentReact.PureComponent ,要么是輸出 JSX 的 function。 其中的兩個例子是

class CustomComponent1 extends React.Component {
  render() { return "I am a component"; }
}

function CustomComponent2 () { 
  return "I am a second component";
}

這兩個都可以在它們自己的文件或其他 JSX 文件中調用,就像這樣。

<CustomComponent1/>
<CustomComponent2/>

但是,以下不能作為組件調用

const SomeArray = ['hello','there'];

// Wrong
<SomeArray/>
// Right
<div>{SomeArray}</div>

本課的重點是在 React 中,除非它是 React 組件(即從前面提到的類之一擴展)或功能組件(返回 JSX 的 function),否則它不是組件,並且不能使用像<CustomComponent/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM