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

React中如何将组件作为prop传递并实现带参条件渲染

修正方案与完整代码

核心问题说明

  • 动态组件渲染语法错误:JSX要求自定义组件必须大写开头,你传入的component prop是小写,会被识别为原生HTML标签,需要先转成大写变量;同时你原来的渲染代码多了一层不必要的大括号包裹。
  • 接口回调逻辑未补全:请求成功/失败后缺少对应状态更新的代码。
  • 缺少错误提示的渲染逻辑:原代码没有展示错误信息的部分。
import { useState } from 'react';

// 接收props时将小写的component重命名为大写的Component,符合JSX组件命名要求
function PatientIDInput({ component: Component }) {
  const [patientID, setPatientID] = useState('');
  const [errorMessage, setErrorMessage] = useState('');
  const [showComponent, setShowComponent] = useState(false);
  const [patientInformation, setPatientInformation] = useState(null);

  const handleChange = (e) => {
    setPatientID(e.target.value);
    // 输入时清空历史错误和旧查询结果
    setErrorMessage('');
    setShowComponent(false);
  }

  const handleSubmit = (e) => {
    e.preventDefault();

    Physician.fetchPatientData(patientID)
      .then(res => {
        if (res.status === 200) {
          // 存储返回的患者数据
          setPatientInformation(res.data);
          // 打开目标组件显示开关
          setShowComponent(true);
          // 清空错误提示
          setErrorMessage('');
        }
      })
      .catch(error => {
        if (error.response?.status) {
          // 设置错误提示
          setErrorMessage('当前输入的ID不存在,请检查后重新输入');
          // 关闭目标组件显示
          setShowComponent(false);
          // 清空旧的患者数据
          setPatientInformation(null);
        }
      })
  }

  return (
    <>
      <form onSubmit={handleSubmit}>
        <input 
          type="text" 
          value={patientID} 
          onChange={handleChange} 
          placeholder="请输入患者ID"
          required
        />
        <button type="submit">查询</button>
      </form>

      {/* 错误提示展示 */}
      {errorMessage && <p style={{ color: 'red', marginTop: '8px' }}>{errorMessage}</p>}

      {/* 目标组件渲染,直接按标准JSX语法传参即可 */}
      {showComponent && <Component patientInformation={patientInformation} />}
    </>
  );
}

export default PatientIDInput;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 23:45:10