这是在 React js 中的按钮 onClick 中调用功能组件的最简单方法
Posted
技术标签:
【中文标题】这是在 React js 中的按钮 onClick 中调用功能组件的最简单方法【英文标题】:Which is the easiest way to call a functional component in button onClick in React js 【发布时间】:2021-05-21 14:14:58 【问题描述】:我在 reactt Js 工作。有人可以建议我在按钮单击时调用功能组件“AddDealItem”的方法。应该是每次我单击按钮时都应该渲染功能组件
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>
)
【问题讨论】:
【参考方案1】:你可以试试这样的
// 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>
【讨论】:
【参考方案2】:这个方法适合我
const useState, Fragment = React;
const [countDealItem, setCountDealItem] = useState(0)
const Deals = () =>
return (
<div className="p-grid p-dir-rev">
<div className="p-col-12 p-md-2">
<Button label="Add Deal Item" onClick=() =>setCountDealItem(countDealItem+1) icon="pi pi-plus" />
Array(countDealItem).fill(<AddDealItem />)
</div>
</div>
)
export default Deals
const AddDealItem = (props: any) =>
const mainStore = useStore();
return (
<Fragment>
"some content"
</Fragment>
)
【讨论】:
以上是关于这是在 React js 中的按钮 onClick 中调用功能组件的最简单方法的主要内容,如果未能解决你的问题,请参考以下文章
React Hooks:useState with onClick 仅更新第二次单击按钮?