【发布时间】:2021-03-02 04:59:40
【问题描述】:
我的想法是<LandingPage> 有<Top>,它会通过用户点击进度来改变。
<Top> 有pageState,然后在First 和Second 页面中单击按钮更改它
这是正确的做法吗?以及如何通过单击First 和Second 页面中的按钮来更改Top 的pageState??
这些是我目前所做的
export default function LandingPage(props) {
return (
<div>
<Header></Header>
<Top></Top>
<Footer></Footer>
</div>
);
}
const Top = (props) =>{
const [pageState, setPageState] = useState([]);
if (pageState == 1){
return (
<Second></Second>
)
}
elif (pageState == 2){
return (
<Third></Third>
)
}
else {
return (
<First></First>
);
}
}
const First = (props) => {
const classes = useStyles();
return (
<Button size="lg" color="success" style={{margin:"50px"}} onClick={()=>***}>
Move to Second page!</Button>
)
}
const Second = (props) => {
return (
<Button size="lg" color="success" style={{margin:"50px"}} onClick={()=>***}>
Move to Third page!!</Button>
);
}
const Third = (props) => {
return (
<div>Third Page</div>
);
}
【问题讨论】:
-
为什么不用react router来导航页面?
-
我已经回答了一个类似的问题here。这是一个原生反应问题,但该方法也可能对这个问题有用。这个想法是您将键和组件(页面)关联起来,并根据状态中的当前键值有条件地呈现组件。如果要更改子组件中父组件的状态,可以通过 props 将状态更新函数 (
setPageState) 传递给子组件并从子组件调用。 -
@Florin 我不想让用户直接访问
Second或Third页面。我的网站就像问卷调查网站每个页面都有 Question1、Question2 或 Question3,我想让用户按顺序移动。 -
@Bas van der Linden 感谢您的评论。
If you want to change the state of a parent component inside a child you could pass the state update function (setPageState) to the child via props and call it from the child.它可能对可能的情况有所帮助。我会试试的。
标签: javascript reactjs material-ui