简体   繁体   中英

ReactJS - Pass multiple functions to child components as a single prop

I am passing multiple function={this.function} as singular props from the parent component to its child components. I don't get any errors or issues with this, but I'm wondering if there's a better / cleaner way to code it.

To illustrate, here is a sample code (the parent component):

import React, { Component } from 'react';

export default class App extends Component {
   function1 = () => {
      // Does something
   };

   function2 = () => {
      // Does something
   };

   function3 = () => {
      // Does something
   };

   function4 = () => {
      // Does something
   };

   function5 = () => {
      // Does something
   };

   render() {
      return (
         <div>
            Parent Component
            
            <ChildComponent 
               function1={this.function1}
               function2={this.function2}
               function3={this.function3}
               function4={this.function4}
               function5={this.function5} />
         </div>
      );
   }
}

It's really just a matter of code becoming a bit long. I'm wondering if there's a short way to pass functions 1 through 5, perhaps in a single line.

Thanks in advance!

Sure, there are at least two options:

import React, { Component } from 'react';

export default class App extends Component {
  functions = {
    function1: () => {
      // Does something
    },

    function2: () => {
      // Does something
    },

    function3: () => {
      // Does something
    },

    function4: () => {
      // Does something
    },

    function5: () => {
      // Does something
    }
  }

  render() {
    return (
      <div>
        Parent Component

        <ChildComponent functions={this.functions} />

        OR

        <ChildComponent {...this.functions} />

      </div>
    );
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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