尝试在带有react的按钮中使用useState时出现空白页面

问题描述 投票:0回答:1

const Button = () =>{
    return (
            <button>My Button</button>
    )
}

export default Button
import React from 'react'
import './App.css'
import Button from "./components/button"
import Image from './components/image'
import { useState } from "react"

const [count, setCount] = useState(0)

const handlerClick = () => {
    setCount(count + 1)
}


const App = () =>{
  return (
    <>
      <Button count ={count} onClick ={handlerClick}/>
    </>
  )
}

export default App
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import './index.css'

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
)

我开始学习反应,我尝试使用 useState 制作按钮来添加数字(我遵循了反应文档,但我已经使用组件创建了按钮,将其导入到应用程序文件中,并将应用程序文件导入到 main.jsx 中为什么我的网页还是空白?

javascript reactjs
1个回答
0
投票
  1. 您不能在组件外部使用

    useState
    (或更新状态的函数)。如果您打开开发者控制台日志 (F12),您应该会收到一些错误。

  2. 当您将道具传递给按钮组件时,按钮组件不会接受任何道具。

const { useState } = React;

// Both the useState hook and the handler
// for updating state are INSIDE the component
function App() {

  const [ count, setCount ] = useState(0);

  function handleClick() {
    setCount(count + 1);
  }

  return (
    <div>
      <p>You clicked {count} times</p>
      <Button
        count={count}
        handleClick={handleClick}
      />
    </div>
  );

}

// Accept the props into the Button component
// so that you can use them
function Button({ count, handleClick }) {
  return (
    <button
      type="button"
      onClick={handleClick}
    >Clicked {count} times
    </button>
  );
}

const node = document.getElementById('root');
const root = ReactDOM.createRoot(node);
root.render(<App />);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.min.js"></script>
<div id="root"></div>

© www.soinside.com 2019 - 2024. All rights reserved.