我正在嘗試渲染一個Alert元件,當一個prop從父元件傳遞給它時,它應該渲染,但是我遇到了一個錯誤
未捕獲的錯誤:物件不是有效的React子元素(找到:具有鍵{message,showAlerts}的物件。如果您想要渲染一個子元素集合,請使用數組代替。
我不確定為什麼React將我的函數元件視為物件。代碼沙盒連結:https://codesandbox.io/s/exciting-smoke-mij6ke?file=/src/App.js:0-3054
這是父元件:
import styled from "styled-components"; import { useTable } from "react-table"; import Alert from "react-bootstrap/Alert"; import Button from "react-bootstrap/Button"; import axios from "axios"; import AppAlerts from "./components/Alerts"; const Styles = styled.div` padding: 1rem; table { border-spacing: 0; border: 1px solid black; tr { :last-child { td { border-bottom: 0; } } } th, td { margin: 0; padding: 0.5rem; border-bottom: 1px solid black; border-right: 1px solid black; :last-child { border-right: 0; } } } `; function Table({ columns, data }) { // Use the state and functions returned from useTable to build your UI const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } = useTable({ columns, data }); const [showAlert, setShowAlert] = useState(false); const [alertMessage, setAlertMessage] = useState(""); const handleButttonClick = () => { setShowAlert(true); setAlertMessage("dummy text"); }; // Render the UI for table return (); } function App() { // const [data, setData] = useState([]); // const [columns, setColumns] = useState([]); const columns = React.useMemo( () => [ { Header: "Id", accessor: "id" }, { Header: "Applicant", accessor: "applicant" }, { Header: "Pincode", accessor: "pincode" }, { Header: "District", accessor: "district" }, { Header: "State", accessor: "state" } ], [] ); const data = React.useMemo( () => [ { id: 18, applicant: "Buzz", pincode: 560096, district: 1, state: 1 }, { id: 19, applicant: "Sue", pincode: 560100, district: 2, state: 1 } ], [] ); return (; {headerGroups.map((headerGroup) => (
{headerGroup.headers.map((column) => ( ))} {rows.map((row, i) => { prepareRow(row); return ({column.render("Header")} ))}{row.cells.map((cell) => { return ( ); })}{cell.render("Cell")} ); })}); } export default App;
子元件:
import { useEffect, useState } from "react"; import Alert from "react-bootstrap/Alert"; export default function AppAlerts(message, showAlerts) { const [show, setShow] = useState(showAlerts); return (setShow(false)} show={show} dismissible > ); }{message}
我在這裡做錯了什麼,我該改變什麼?
我嘗試以我認為被接受的方式渲染Alerts的子元件。點擊按鈕後,Alert元件必須渲染並開啟警報框。在關閉警報時,父元件中顯示警報的狀態變數(showAlerts)也必須變更為'false'。
將下面這句話翻譯成中文,保留html程式碼,不用增加新內容:
變成:
因為props總是一個對象,並且它們作為第一個參數傳遞。
在參數清單中使用花括號表示你正在解構第一個參數(即props參數)。