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

标签 reactjs

我是 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/

相关文章:

javascript - Node.js 服务器用 React.JS 覆盖整个 DOM

javascript - React 上的 componentWillReceiveProps 在触发时不会传递当前属性

javascript - 找不到模块 : Error: Cannot resolve module 'react-redux'

node.js - 如何将react数据发布到express

javascript - 我在哪里以及如何在 reactjs 应用程序中指定全局变量

javascript - 生成日期并将新属性添加到对象数组中

javascript - 即使缺少 prop,我怎样才能让我的 React 子组件呈现

reactjs - 更改 nginx 默认文件夹

javascript - 三元运算符在 React 组件中用于设置数据列表选项的值时失败

javascript - React.js - 从父组件调用函数