javascript - 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>
)
}
解决方案
你可以试试这样的
// 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>
推荐阅读
- linux - 无法运行 Cryptogen
- python - 如何将输入列表传递给 Python 中的构造函数?
- media-player - 视频被分割成各种无媒体文件
- microservices - 使用 Eureka 时应该把什么作为可发现的服务?
- acumatica - 尝试自定义 JAMS LaborEntry 屏幕,寻找将更新标题的代码行
- c++ - FormatMessage 为 d3d11 错误返回 0。如何获取 d3d11 错误的错误描述?
- javascript - 使用值数组过滤 GeoJSON 数据以创建 Leaflet 地图
- javascript - TS 编译器/create-react-app 从函数中移除异步
- android - 根据内容高度的变化调整 PopupWindow 的大小
- android - 如何使用 Recycler View 实现评论部分