繁体   English   中英

ReactJS - 将多个功能作为单个道具传递给子组件

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

我将多个function={this.function}作为单数道具从父组件传递到其子组件。 我没有收到任何错误或问题,但我想知道是否有更好/更清洁的编码方式。

为了说明,这里是一个示例代码(父组件):

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>
      );
   }
}

这实际上只是代码变得有点长的问题。 我想知道是否有一种简短的方法可以通过函数 1 到 5,也许在一行中。

提前致谢!

当然,至少有两种选择:

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>
    );
  }
}

暂无
暂无

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

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