首页 > 解决方案 > Which is the easiest way to call a functional component in button onClick in React js

问题描述

I am working in reactt Js . Can some one suggest me a way to call the functional component "AddDealItem" on button click . It should be in away that each time I click the button the functional component should get rendered


    const Deals = () => {
     return (
          <div className="p-grid p-dir-rev">
            <div className="p-col-12 p-md-2"> 
              <Button label="Add Deal Item" icon="pi pi-plus" />
             </div>
           </div>
          )
       }
 export default Deals
    
    
    const AddDealItem = (props: any) => {
        const { mainStore } = useStore();
        
        return (
            <Fragment>
                "some content"
            </Fragment>
    
        )
    }

标签: javascriptreactjsrenderingreact-componentreact-functional-component

解决方案


你可以试试这样的

// This is just for this example, import useState and Fragment as usual from react
const {useState, Fragment} = React;
 
const AddDealItem = (props) => {
  // const { mainStore } = useStore(); commented out for the running snippet

  return <Fragment>"some content"</Fragment>;
};

const Deals = () => {
  const [showAdd, setShowAdd] = useState(false);

  return (
    <div className="p-grid p-dir-rev">
      <div className="p-col-12 p-md-2">
        <button
          onClick={() => setShowAdd((showAdd) => !showAdd)}
          label="Add Deal Item"
          icon="pi pi-plus"
        >
          Show Add
        </button>
        {showAdd && <AddDealItem />}
      </div>
    </div>
  );
};

// Render it
ReactDOM.render(<Deals />, 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>


推荐阅读