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

React 16.8登录系统:如何在render外跨组件传递props?

React 16.8登录系统:解决在render外传递props给Welcome组件的问题

嘿,我看到你遇到的这个错误了——Expected an assignment or function call and instead saw an expression,本质原因是你在Control方法里直接写了<Welcome uName={user.username} />这个JSX表达式,但它既没有被赋值给变量,也没有作为返回值,更关键的是:React组件的渲染是由状态驱动的,你不能在事件处理函数里直接渲染组件,得通过更新状态让render方法来处理这件事。

咱们一步步来修复这个问题:

1. 给LoginControl添加登录状态

首先在组件的state里添加两个新属性:isLoggedIn(标记是否登录成功)和currentUser(存储登录成功的用户信息),这样登录成功后可以通过更新状态触发组件重新渲染。

2. 重构Control方法

  • 不要用document.getElementById获取输入值(React更推荐受控组件,不过这里先按你的思路调整);
  • 找到匹配的用户后,通过setState更新登录状态和当前用户,而不是直接渲染Welcome组件;
  • 注意map方法在这里不合适,应该用find来查找匹配的用户(因为我们只需要找到第一个匹配的用户)。

3. 在render方法里根据状态渲染Welcome组件

当isLoggedIn为true时,渲染Welcome组件并传递uName props;否则显示登录按钮。

修改后的LoginSystem.jsx代码

import React from 'react';
import Welcome from "./Welcome"

class LoginControl extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      users: [
        { username:"code", password:"blogger" },
        { username:"true", password:"codes" },
        { username:"furkan", password:"gulsen" }
      ],
      isLoggedIn: false,
      currentUser: null
    }
  }

  Control = () => {
    const usernameInput = document.getElementById("username");
    const passwordInput = document.getElementById("password");
    
    // 用find查找匹配的用户,而不是map
    const matchedUser = this.state.users.find(user => 
      user.username === usernameInput.value && user.password === passwordInput.value
    );

    if(matchedUser) {
      // 更新状态,触发render重新执行
      this.setState({
        isLoggedIn: true,
        currentUser: matchedUser
      });
      // 可选:清空输入框
      usernameInput.value = '';
      passwordInput.value = '';
    } else {
      alert("用户名或密码错误!");
    }
  };

  render(){
    // 根据登录状态决定渲染内容
    if(this.state.isLoggedIn) {
      return <Welcome uName={this.state.currentUser.username} />;
    }

    return(
      <div>
        {/* 补充原代码缺失的输入框 */}
        <input type="text" id="username" placeholder="用户名" />
        <input type="password" id="password" placeholder="密码" />
        <button className="btn btn-success" onClick={this.Control}>Sign In</button>
      </div>
    )
  }
}

export default LoginControl;

Welcome.jsx保持不变

import React from 'react'

const Welcome = (props) => {
  return(
    <h2>WELCOME {props.uName}</h2>
  )
}

export default Welcome;

为什么原来的代码会报错?

你在map里写的<Welcome uName={user.username} />只是一个JSX表达式,它没有被任何地方使用(既没赋值也没返回),ESLint会认为这是一个无用的表达式,所以抛出no-unused-expressions错误。而且React的组件渲染逻辑是由render方法控制的,直接在事件处理函数里渲染组件不会触发DOM更新,必须通过状态变化让render重新渲染对应内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:17:36