如何做:点击时仅替换一个组件(动态用户界面)

时间:2019-08-22 16:11:03

标签: html reactjs

使用react.js我想创建一个动态UI,我有这样的东西:

<div>
  <appbar component />
  <drawer (sidebar) comopnent /> <!-- <--has buttons -->
  <content component> <!-- <-- component to replace or re-render -->
  <footer component>
</div>

然后我尝试使用一种状态来保存和更改“”,如下所示:

 const [renderView, setRenderView] = useState("<Home />");

/* onclick call this function and pass referenced component ej: <reports /> */

function changeContent(view){ 
        setRenderView(view);

        return(
         <Suspense fallback={renderLoader()}>
            {view}
        </Suspense>
        );

    }

现在,如何用新组件替换“内容组件”?

感谢您的评论。

1 个答案:

答案 0 :(得分:0)

我在建议,工作原理上大加赞扬,但我没有使用类纯函数

功能仪表板(道具){

/* lazy loading */
const renderLoader = () => <p>Loading...!?¡?</p>;

/* lazy components */
const Initial = () => (
  <Suspense fallback={renderLoader()}>
      <InitialComponent />
  </Suspense>
)
const Reports = () => (
    <Suspense fallback={renderLoader()}>
        <ReportsComponent />
    </Suspense>
)
const Cards = () => (
  <Suspense fallback={renderLoader()}>
      <CardsComponent />
  </Suspense>
)

/* set view state */
const [renderView, setRenderView] = useState(Initial());

function changeContent(view){
    setRenderView(view);

}

const test = (cosa) => {
  console.log(cosa);
}

/* style things*/
const classes = useStyles();
const fixedHeightPaper = clsx(classes.paper, classes.fixedHeight);

return (
    <div className={classes.root}>
    <CssBaseline />
    <UIappbar />
    <UIsidebar />
    <main className="contentWrapper">
        <Grid container spacing={3}>
            <Grid item xs={12} md={8} lg={9}>
            <div>
                <Button onClick={() => changeContent(Reports())}>Reports view</Button>
            </div>
            <div>
                <Button onClick={() => changeContent(Cards())}>Cards view</Button>
            </div>
            </Grid>
            <Grid item xs={12} md={8} lg={9}>
                <Paper className={fixedHeightPaper}>
                {renderView}
                </Paper>
            </Grid>
        </Grid>
    </main>
    </div>
);

}

现在,我需要调用具有更改{renderView}方法的“ changeContent()”,需要从子级调用它 不知道如何传递没有类格式的道具(仅使用函数)

我应该改为使用构造函数格式的类吗?