reactjs React单页

pinkon5k  于 2023-03-08  发布在  React
关注(0)|答案(1)|浏览(103)

我有一个组件的内容,我的网页...它是如下:

import React from 'react';
import '../styles/content.css';
import Home from './home';

const Content = ()=>{
    return(
        <div className='contain-content'>
            <Home/>
            
        </div>
    );
}

export default Content;

我还有另一个组件菜单,其中包含一些包含“Buttons”的div:

const IcoMenu = () => {
  return (
    <div className="menu-contain" >
      <div id="home" className="ico-menu">...</div>
      <div id="resume" className="ico-menu">...</div>
    </div>
  );
 }

我是React的新手,我想实现的是当我单击按钮时,它会更新Content组件...并将Home组件更改为另一个组件。

chhqkbe1

chhqkbe11#

import React, { useState } from 'react';
import '../styles/content.css';
import Home from './home';
import OtherComponent from './otherComponent';
import IcoMenu from './IcoMenu';

const Content = () => {    
  const [currentPage, setCurrentPage] = useState('home');

  const renderPage = () => {
    if (currentPage === 'home') {
      return <Home />;
    } else if (currentPage === 'other') {
      return <OtherComponent />;
    }
  };

  return (
    <div className='contain-content'>
      <IcoMenu setCurrentPage={setCurrentPage}/>
      {renderPage()}
    </div>
  );
};

export default Content;

您可以向IcoMenu组件中的每个按钮传递一个函数,以便在单击时更新Content组件的状态:

const IcoMenu = ({setCurrentPage}) => {
  const handleClick = (page) => {
    setCurrentPage(page);
  };

  return (
    <div className="menu-contain" >
      <div id="home" className="ico-menu" onClick={() => handleClick('home')}>
        ...
      </div>
      <div id="other" className="ico-menu" onClick={() => handleClick('other')}>
        ...
      </div>
    </div>
  );
};

相关问题