【问题标题】:How to pass component as a prop and render it conditionally?如何将组件作为道具传递并有条件地渲染它?
【发布时间】:2022-01-06 20:21:37
【问题描述】:

我这里有一个组件,它获取一个 ID 号并检查该 ID 号是否存在于数据库中。如果它存在,它应该呈现一个组件,如果不存在则显示错误消息。正在为如何编写而苦苦挣扎,不胜感激。

function PatientIDInput({component}) {
  const [patientID, setPatientID] = useState('');
  const [errorMessage, setErrorMessage] = useState('');
  const [showComponent, setShowComponent] = useState(false);
  const [patientInformation, setPatientInformation] = useState('');

  const handleChange = (e) => {
    // some input change handling
  }

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

    Physician.fetchPatientData(patientID)
      .then(res => {
        if (res.status === 200) {
            // show component if patient exists
        }
      })
      .catch(error => {
        if (error.response.status) {
          // set error if not
        }
      })
  }

  return (
    <>
    <form onSubmit={handleSubmit}>
               // some UI code for user's input
    </form>

    { showComponent 
      ? {Component patientInformation={patientInformation}} />  // this is where I'm 
                   struggling with the syntax. How should I write the logic? I want to pass
                   some props to the component too.
      : null}
    </>
  );
}

export default PatientIDInput;

【问题讨论】:

    标签: javascript reactjs frontend react-component web-frontend


    【解决方案1】:

    以下是我最常用的一些模式。

    传递一个“反应组件”

    function PatientIDInput({Component}) {
      // skip
      return (
        <>
        <form onSubmit={handleSubmit}>
                   // some UI code for user's input
        </form>
    
        { showComponent 
          ? <Component patientInformation={patientInformation} />
          : null}
        </>
      );
    }
    
    export default PatientIDInput;
    
    const Sample = ({ patientInformation }) => <div>{patientInformation}</div>
    <PatientIDInput Component={Sample} />
    

    将“渲染函数”作为子项传递

    function PatientIDInput({children}) {
      // skip
      return (
        <>
        <form onSubmit={handleSubmit}>
                   // some UI code for user's input
        </form>
    
        { showComponent 
          ? children({ patientInformation  })
          : null}
        </>
      );
    }
    
    export default PatientIDInput;
    
    const Sample = ({ patientInformation }) => <div>{patientInformation}</div>
    <PatientIDInput>
      {({ patientInformation }) => <Sample patientInformation ={patientInformation} />}
    </PatientIDInput>
    

    将“React 元素”作为子项传递

    function PatientIDInput({children}) {
      // skip
      return (
        <>
        <form onSubmit={handleSubmit}>
                   // some UI code for user's input
        </form>
    
        { showComponent 
          ? React.cloneElement(children, { patientInformation  })
          : null}
        </>
      );
    }
    
    export default PatientIDInput;
    
    const Sample = ({ patientInformation }) => <div>{patientInformation}</div>
    <PatientIDInput>
      <Sample/>
    </PatientIDInput>
    

    【讨论】:

    • 正是我想要的。谢谢。
    【解决方案2】:

    你可以使用

    React.cloneElement(
      element,
      [config],
      [...children]
    )
    

    使用 element 作为起点克隆并返回一个新的 React 元素。 config 应该包含所有新的 props、key 或 ref。生成的元素将具有原始元素的 props 和浅层合并的新 props。新的孩子将取代现有的孩子。如果配置中不存在 key 和 ref,则原始元素中的 key 和 ref 将被保留。

    例子

    import React from "react";
    
    function Child(props) {
      return <div>{props.name}</div>;
    }
    
    function SomeOtherComponent(props) {
      return (
        <>
          {React.cloneElement(props.component, {
            someFunction: () => {
              console.log("inside callback");
            },
            name: "Ganesh",
          })}
        </>
      );
    }
    
    function App() {
      return (
        <div>
          Hi
          <SomeOtherComponent component={<Child />}></SomeOtherComponent>
        </div>
      );
    }
    

    【讨论】:

    • 提供参考 :) 最好作为链接。对于这种情况,api-reference 就足够了。
    【解决方案3】:

    不要将组件作为道具传递,而是直接在 PatientIdInput 组件中导入组件,然后将 patientInformation 作为道具传递给它,如下所示:

    **Import your Component Here**
    
    function PatientIDInput({component}) {
      const [patientID, setPatientID] = useState('');
      const [errorMessage, setErrorMessage] = useState('');
      const [showComponent, setShowComponent] = useState(false);
      const [patientInformation, setPatientInformation] = useState('');
    

    返回部分:

     return (
       <>
        <form onSubmit={handleSubmit}>
               // some UI code for user's input
        </form>
    
      { showComponent 
        ? <ImportedComponent patientInformation={patientInformation}/>
      : null}
    </>
      );
    }
    
    export default PatientIDInput;
    

    【讨论】:

    • 这应该是一条评论。没有答案。
    • 这和我之前写的代码很相似。不幸的是,组件 PatientIDInput 必须在项目的其他部分重用——因此这个线程。
    猜你喜欢
    • 2021-09-08
    • 2017-12-19
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 2023-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多