You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React表单提交后用户名消息不显示问题求助

问题解决方法

你的代码存在两个核心问题导致功能失效:

  1. 提交按钮未指定type="submit"
    React Bootstrap的Button组件默认类型是button,无法触发表单的onSubmit事件。必须显式设置type="submit",点击按钮时才会执行提交逻辑。

  2. 状态存储方式不够合理(可选优化)
    你直接将JSX元素存在message状态中,这并非React状态的最佳使用方式。建议存储用户名字符串,渲染时再生成对应的JSX结构,让状态更纯粹、易维护。

另外,onChange回调里的console.log(username)会打印旧值——因为useState的状态更新是异步的,若需要查看最新值,可直接使用event.target.value,或通过useEffect监听状态变化。

修复后的完整代码:

import './App.css';
import { Button, Container, Form } from 'react-bootstrap';
import { useState } from 'react';

function App() {
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [message, setMessage] = useState('')

  function handleSubmit(event) {
    event.preventDefault();
    setMessage(username)
  }

  return (
    <Container>
      <Form onSubmit={handleSubmit}>
        <Form.Group>
          <Form.Label>Username</Form.Label>
          <Form.Control 
            value={username} 
            onChange={(event) => setUsername(event.target.value)} 
          />
        </Form.Group>
        <Form.Group>
          <Form.Label>Password</Form.Label>
          <Form.Control 
            value={password} 
            onChange={(event) => setPassword(event.target.value)} 
          />
        </Form.Group>
        <Button className='mt-3' type="submit">Submit</Button>
      </Form>
      {message && <h1>{message}</h1>}
    </Container>
  )
}

export default App;

关键修改说明

  • 给Button添加type="submit",确保点击触发表单提交
  • 将message状态改为存储用户名字符串,渲染时通过条件判断生成JSX
  • 移除了异步状态导致的无效console.log,避免混淆

内容的提问来源于stack exchange,提问作者Tazeen Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 22:19:50