gpt4 book ai didi

javascript - 在同一页面加载ReactJS组件覆盖其他组件

转载 作者:行者123 更新时间:2023-12-02 23:39:29 24 4
gpt4 key购买 nike

我有一个包含其他组件的主页组件。其中一个组件是多步骤注册表单,包含三个步骤 - 1. 选择计划、2. 帐户详细信息和 3. 感谢页面。主页组件显示多步骤注册表单的第一步,即选择计划组件。

单击计划后,我希望在同一页面上打开“帐户”组件,覆盖“主页”组件,而不是替换当前组件。同时,我希望将 props 传递给子组件。

包含注册表单的主页组件

class Home extends Component {
render() {
return (
<div>
<Video/>
<Featured/>
<SignUpForm />
</div>
);
}
}

多步骤注册表单 -

import React, { Component } from "react";
import Plan from "./Plan";
import Account from "./Account";
import ThankYou from "./ThankYou";

export default class SignUpForm extends Component {
state = {
step: 1,
account_type: "",
first_name: "",
last_name: "",
email: "",
password: "",
};

// Proceed to next step
nextStep = () => {
const { step } = this.state;
this.setState({
step: step + 1
});
console.log(this.state.step);
};

// Go back to previous step
prevStep = () => {
const { step } = this.state;
this.setState({
step: step - 1
});
};

// Handle fields change
handleChange = input => e => {
this.setState({ [input]: e.target.value });
};

render() {
const { step } = this.state;
const {
account_type,
price,
first_name,
last_name,
email,
password,
token
} = this.state;
const values = {
account_type,
price,
first_name,
last_name,
email,
password,
token
};

switch (step) {
case 1:
return (
<Plan
nextStep={this.nextStep}
handleChange={this.handleChange}
values={values}
/>
);
case 2:
return (
<Account
nextStep={this.nextStep}
prevStep={this.prevStep}
handleChange={this.handleChange}
values={values}
/>
);
case 3:
return <ThankYou />;

}
}
}

最佳答案

那么您希望 Home 组件的孙子组件覆盖 home 组件吗?你根本不能这样做。

如果您想要覆盖的原因是您不想显示 VideoFeatured 组件,只需将“step”逻辑向上移动到 主页组件。然后你可以像这样返回:

switch (step) {
case 1:
return (
<Video />
<Featured />
<Plan
nextStep={this.nextStep}
handleChange={this.handleChange}
values={values}
/>
);
case 2:
return (
<Account
nextStep={this.nextStep}
prevStep={this.prevStep}
handleChange={this.handleChange}
values={values}
/>
);
case 3:
return (
<Video>
<Featured />
<ThankYou />
);

}

如果您确实想替换 H​​ome 组件,请将所有逻辑向上移动一个组件,即高阶组件。

class MyComponent extends React.Component {

\\all your logic and inside the render function:
switch (step) {
case 1:
return (
<Home {...props}/>
);
case 2:
return (
<Account
{...props}
/>
);
case 3:
return (
<Home {...props}/>
);

}
}

请记住,当向上移动逻辑时,状态会成为较低组件中的 props,并且您需要将较高组件中逻辑中的状态作为 props 向下传递。

关于javascript - 在同一页面加载ReactJS组件覆盖其他组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56139794/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com