按钮单击以渲染Div

时间:2020-08-27 13:25:46

标签: reactjs

我想单击按钮并渲染其对应的div。是否应将要渲染的div信息添加到状态? 我敢肯定有几种不同的方法可以解决这个问题,但我想以React的方式来实现,或者可以作为功能组件来实现?

已更新

       export default function About(props) (
        const [isHidden, setIsHidden] = useState(true);

        const handleClick = () => {
        setIsHidden(!isHidden);
        };
         return (

       <div className="row justify-content-md-center">
        <div className="col-auto">
          <CustomButton onClick={handleClick}>Website Develpment</CustomButton>
        </div>
        <div className="col-auto">
          <CustomButton onClick={handleClick}>Wordpress Develpment</CustomButton>
        </div>
        <div className="col-auto">
          <CustomButton onClick={handleClick}>Ecommerce Development</CustomButton>
        </div>
      </div>

      <div className="row">
        <div className="col-md-4">column 1</div>
        <div className="col-md-4">column 2</div>
        <div className="col-md-4">column 3</div>
      </div>
     );
    )

4 个答案:

答案 0 :(得分:1)

您可以将ID存储为字符串状态变量,并在按下按钮时设置该变量。

然后使用ConditionalRendering仅显示具有匹配ID的div。

const {useState} = React;

function About(props) {
  const [visibleItem, setVisibleItem] = useState('');
  return (
    <div>
      <button onClick={() => setVisibleItem("website")}>
        Show Website Develpment
      </button>
      <button onClick={() => setVisibleItem("wordpress")}>
        Show Wordpress Develpment
      </button>
      <button onClick={() => setVisibleItem("ecommerce")}>
        Show Ecommerce Development
      </button>
      
      {visibleItem === "website" && 
        <div>
          <h2>Wordpress Development</h2>
          <p>Info about Wordpress and all the things I can do with it</p>
        </div>
      }     
      
      {visibleItem === "wordpress" && 
        <div>
          <h2>Ecommerce Development</h2>
          <p>I can do eccomerce things too</p>
        </div>
      }      
      
      {visibleItem === "ecommerce" && 
         <div>
          <h2>Website Development</h2>
          <p>Info about Webdev</p>
        </div>
      }
      
    </div>
   );
}

ReactDOM.render(
  <About/>,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>

如果这些部分要大得多,那么我建议将它们分成单独的组件,或者执行ifswitch语句以在return之前在它们之间进行选择,但是上面的代码段是我经常在react上使用的模式。

答案 1 :(得分:0)

您可以创建两种状态,一种是保存按钮信息的数组以最大程度地减少代码的重复,另一种状态是跟踪单击的列。

 import React, { useState } from "react";
    
    export default function About(props) {
      const [colNum, setColNum] = useState('');
      const [btnNames] = useState([
        {
          colId: 1,
          name: "Website Develpment"
        },
        {
          colId: 2,
          name: "Wordpress Develpment"
        },
        {
          colId: 3,
          name: "Ecommerce Develpment"
        }
      ]);
    
      const handleClick = (id) => {
        setColNum(id);
      };
    
      return (
        <>
          <div className="row justify-content-md-center">
            {btnNames.map(element => (
              <div className="col-auto" key={element.colId}>
                <CustomButton onClick={()=> handleClick(element.colId)}>{element.name}</CustomButton>
              </div>
            ))}
          </div>
    
          {colNum !== '' ? (<div className="row">
            <div className="col-md-4">column {colNum}</div>
            </div>) : null }
          
        </>
      );
    }

答案 2 :(得分:0)

因此,您可以为状态中的每个部分定义显示值,其初始值应为false。然后,我们可以使用可以使用内置JS工具(Object.entriesObject.fromEntriesmap)的函数来处理此状态。将显示该元素,其值将为true,其余元素将自动变为false。可在此处找到更多详细信息:https://codesandbox.io/s/happy-sea-nckmw?file=/src/App.js

import React, { useState } from "react";
import "./styles.css";
import styles from "./TestStyles.module.css";
import CustomButton from "./CustomButton";

export default function App() {
  const [showDiv, setShowDiv] = useState({
    web: false,
    wordpress: false,
    ecommerce: false
  });

  const showDivHandler = (val) => {
    const newState = Object.fromEntries(
      Object.entries(showDiv).map(([key, value]) => [key, (value = false)])
    );

    setShowDiv({
      ...newState,
      [val]: !showDiv[val]
    });
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <div className={styles.Section}>
        <div className="col-auto">
          <CustomButton clicked={() => showDivHandler("web")}>
            Website Develpment
          </CustomButton>
        </div>
        <div className="col-auto">
          <CustomButton clicked={() => showDivHandler("wordpress")}>
            Wordpress Develpment
          </CustomButton>
        </div>
        <div className="col-auto">
          <CustomButton clicked={() => showDivHandler("ecommerce")}>
            Ecommerce Development
          </CustomButton>
        </div>
      </div>
      <div className={styles.Section} style={{marginTop: 20}}>
        {showDiv.web && <div className={styles.Content}>column 1</div>}
        {showDiv.wordpress && <div className={styles.Content}>column 2</div>}
        {showDiv.ecommerce && <div className={styles.Content}>column 3</div>}
      </div>
    </div>
  );
}

自定义按钮如下所示:

import React from "react";

const button = (props) => (
  <button
    onClick={props.clicked}
    //some other props if need it(e.g. styles)
  >
    {props.children}
  </button>
);

export default button;

答案 3 :(得分:0)

这就是我解决的方法。感谢您的帮助!

export default function About() {
  const [visibleItem, setVisibleItem] = useState(1);

  const [priceItems] = useState([
    {
      id: 1,
      name: "website",
    },
    {
      id: 2,
      name: "wordpress",
    },
    {
      id: 3,
      name: "ecommerce",
    },
  ]);

  const handleClick = (id) => {
    setVisibleItem(id);
  };
  return (
    <div className="container-fluid pricing-wrapper">
      <div className="row">
        <div className="col">
          <h1>Pricing</h1>
        </div>
      </div>

      <div className="row">
        <div className="col">
          <p>Innovation that empowers your team while also reducing risk!</p>
          <div className="seperator"></div>
        </div>
      </div>

      <div className="row justify-content-md-center">
        <div className="row justify-content-md-center">
         {priceItems.map((item) => (
           <div className="col-auto">
              <CustomButton onClick={() => setVisibleItem(item.id)}>
               {item.name}
              </CustomButton>
          </div>
         ))}
          </div>
      </div>

      {priceItems
        .filter((item) => item.id === visibleItem)
        .map((item) => (
          <PriceItem item={item} />
        ))}
    </div>
  );
}