首页 > 解决方案 > 如何将模态从当前组件移动到自己的组件中

问题描述

如何为模式制作单独的组件,这取决于 React 中当前组件中的 API 调用

我有以下 API 调用

class Designs extends Component {
//after constructor I have a function which makes an api call:
async componentDidMount() {
    const designs = await axios.get(`${DESIGN}`);
    this.setState({ rawDesigns: designs.data.documents }); //rawDesigns is an array

我在渲染方法中有以下模式

render() {
    const {
      designs,
      showModal,
      selectedDesign,
      rawDesigns,
      currentStep,
    } = this.state;

return(
 {showModal && (
          <Modal toggleModal={this.togglePageModal} pageModal={true}>
            <h2 style={{ textAlign: "center", width: "100%" }}>
              {rawDesigns[selectedDesign].name}
            </h2>
            <span
              style={{
                textAlign: "center",
                width: "100%",
                letterSpacing: "3px !important",
                fontWeight: "bold",
                color: "#5252ED",
                marginTop: "5px"
              }}
            >
              {currentStep === 1 && `BASIC DETAILS`}
              {currentStep === 2 && `ARCHITECTURE`}
              {currentStep === 3 && `TEAMS`}
            </span>
            <DotSteps
              totalSteps={3}
              currentStep={currentStep}
              onChange={currentStep => this.setState({ currentStep })}
              className="flex-jfe"
            />
            {currentStep === 1 && (
              <div className="w-100 flex flex-col">
                <ContentCard>
                  <span style={{ color: "#5252ED", fontWeight: "bold" }}>
                    Type
                  </span>
                  <h3 className="mt0">{rawDesigns[selectedDesign].type}</h3>
                </ContentCard>

如您所见,此模式使用状态变量以及来自Designs组件中 api 调用的信息。我是否可以为此模式创建一个单独的组件,然后在 render 方法中使用它Designs

标签: javascriptreactjsapimodal-dialog

解决方案


React Portal 提供了一种一流的方式来将子级渲染到存在于父组件的 DOM 层次结构之外的 DOM 节点中。

https://reactjs.org/docs/portals.html


推荐阅读