简体   繁体   English

如何使用 onClick 事件调用基于 class 的组件中的功能组件?

[英]how to call functional component in class based component using onClick event?

i want to show my functional component in class base component but it is not working.我想在 class 基本组件中显示我的功能组件,但它不起作用。 i made simpletable component which is function based and it is showing only table with some values but i want to show it when i clicked on Show user button.我制作了基于 function 的简单组件,它只显示带有一些值的表格,但我想在单击“显示用户”按钮时显示它。

import React ,{Component} from 'react';
import Button from '@material-ui/core/Button';
import SimpleTable from "../userList/result/result";


 class ShowUser extends Component{
     constructor(props) {
         super(props);
         this.userList = this.userList.bind(this);
     }
     userList = () => {
         //console.log('You just clicked a recipe name.');
         <SimpleTable/>
   }

    render() {

         return (
             <div>

                 <Button variant="contained" color="primary" onClick={this.userList} >
                     Show User List
                 </Button>

             </div>
         );
     }


}
export default ShowUser;

If you're referring to the method userList then it appears that you're assuming there is an implicit return value.如果您指的是方法userList ,那么您似乎假设存在隐式返回值。 Because you're using curly braces you need to explicitly return from the function meaning:因为您使用的是花括号,所以您需要从 function 显式返回含义:

const explicitReturn = () => { 134 };
explicitReturn();  <-- returns undefined

const implicitReturn = () => (134);
implicitReturn(); <-- returns 134

The problem lies with how you are trying to display the SimpleTable component.问题在于您如何尝试显示SimpleTable组件。 You are using it inside the userList function, but this is incorrect.您在userList function 中使用它,但这是不正确的。 Only use React elements inside the render method.仅在 render 方法中使用 React 元素。

What you can do instead is use a state, to toggle the display of the component.您可以做的是使用 state 来切换组件的显示。 Like this:像这样:

 const SimpleTable = () => ( <p>SimpleTable</p> ); class ShowUser extends React.Component { constructor(props) { super(props); this.state = {showSimpleTable: false}; this.toggle= this.toggle.bind(this); } toggle = () => { this.setState(prev => ({showSimpleTable: .prev;showSimpleTable})). } render() { return ( <div> <button variant = "contained" color = "primary" onClick={this.toggle}> Show User List </button> {this.state;showSimpleTable && <SimpleTable />} </div> ). } } ReactDOM,render(<ShowUser />. document;getElementById("app"));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="app"></div>

The functionality you are looking for is called Conditional Rendering .您正在寻找的功能称为条件渲染 The onClick prop function is an event handler and events in react may be used to change the state of a component. onClick prop function 是一个事件处理程序,react 中的事件可用于更改组件的 state。 That state then may be used to render the components.然后可以使用 state 来渲染组件。 In normal vanilla javascript or jQuery we call a function and modify the actual DOM to manipulate the UI.在普通的香草 javascript 或 jQuery 中,我们调用 function 并修改actual DOM以操纵 UI。 But React works with a virtual DOM .但是 React 使用virtual DOM You can achieve the functionality you are looking for as follows:您可以按如下方式实现您正在寻找的功能:

class ShowUser extends Component {
    constructor(props) {
        super(props)

        // This state will control whether the simple table renders or not
        this.state = {
            showTable: false
        }

        this.userList.bind(this)
    }

    // Now when this function is called it will set the state showTable to true
    // Setting the state in react re-renders the component (calls the render method again)
    userList() {
        this.setState({ showTable: true })
    }

    render() {
        const { showTable } = this.state

        return (
            <div>
                <Button variant="contained" color="primary" onClick={this.userList}>
                    Show User List
                </Button>

                {/* if showTable is true then <SimpleTable /> is rendered if falls nothing is rendered */}
                {showTable && <SimpleTable />}
            </div>
        )
    }
}

Why your code is not working为什么您的代码不起作用

  1. SimpleTable has to be rendered, so you need to place it inside the render method. SimpleTable 必须被渲染,所以你需要将它放在 render 方法中。 Anything that needs to be rendered inside your component has to be placed there任何需要在组件内渲染的东西都必须放在那里
  2. On Click can just contain SimpleTable, it should be used to change the value of the state variable that controls if or not your component will be shown. On Click 只能包含 SimpleTable,它应该用于更改 state 变量的值,该变量控制是否显示您的组件。 How do you expect this to work, you are not rendering the table.您希望这如何工作,您没有渲染表格。

Below is how your code should look like to accomplish what you want:下面是你的代码应该如何完成你想要的:

import React ,{Component} from 'react';
import Button from '@material-ui/core/Button';
import SimpleTable from "../userList/result/result";


class ShowUser extends Component{
 constructor(props) {
     super(props);
     this.state = { showUserList : false }
     this.userList = this.userList.bind(this);
 }
 showUserList = () => {
     this.setState({ showUserList : true });
 }

render() {

     return (
         <div>

             <Button variant="contained" color="primary" onClick={this.showUserList} >
                 Show User List
             </Button>
         {this.state.showUserList ? <SimpleTable/> : null}

         </div>
     );
 }


}
export default ShowUser;

You can also add a hideUserList method for some other click.您还可以为其他单击添加 hideUserList 方法。

Or even better a toggleUserList甚至更好的是 toggleUserList

this.setState({ showUserList : !this.state.showUserList});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM