gpt4 book ai didi

reactjs - 在按钮单击事件上调用组件

转载 作者:行者123 更新时间:2023-12-02 03:12:14 26 4
gpt4 key购买 nike

我是 React.js 新手,我想在按钮单击事件上调用我的组件。

我的要求是,当我单击“下一步”按钮时,我应该调用下一个组件。我尝试使用 onClick 事件并传递函数,该函数返回 .jsx 代码。但它没有渲染。

有人可以帮我吗?

import React, { Component } from "react";
import { Button } from "antd";

class GoNext extends Component {
render() {

const nextCategory = () => {
return <Category2 />;
};
const renderNext = () => {
return (
<div>
<Button type="primary" onClick={nextCategory}>
Next Category
</Button>
</div>
);
};

return (
<div>
<h4>Successfully Submit!!!</h4>
{renderNext}
</div>
);
}
}

export default GoNext;

最佳答案

考虑一下:

  • 首先:要使按钮呈现,我们需要调用该函数,当然还要添加 this. 以便它在组件中实际找到它:

    <
  • 第二:我们希望在状态中有一个属性,它告诉要渲染哪个类别(如果将来有多个类别)。


import React, { Component } from "react";
import { Button } from "antd";

class GoNext extends Component {
state = {
activeCategory: 0
}

// Each time the button is clicked will add 1 to the activeCategory
// when that happens a re-render will occur, if 1 is defined as a case in the switch inside renderCategory, it should render a component...
handleNextCatClick = () => {
this.setState(prevState => ({
activeCategory: prevState.activeCategory + 1
}));
}

renderCategory = () => {
const { state: { activeCategory } } = this;
switch(activeCategory){
case 0: return <Category2 />;
// Add more cases if you wish such like case 1, case 2 ...etc
default: return null
}
};

renderNextCatButton = () => {
return (
<div>
<Button type="primary" onClick={handleNextCatClick}>
Next Category
</Button>
</div>
);
};

render() {

return (
<div>
<h4>Successfully Submit!!!</h4>
{this.renderCategory()}
{this.renderNextCatButton()}
</div>
);
}
}

export default GoNext;

关于reactjs - 在按钮单击事件上调用组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57264955/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com