使用附加参数将动作传递函数反映到动态创建的子项

问题描述 投票:0回答:1

我想动态创建子组件,从React中的父/祖父组件接收onClick事件。在创建过程中,我想为onClick事件添加一个参数。基本上所需的流程是:

  • 渲染父组件时
  • 将对所需函数的引用传递给动态组件的创建
  • 在创建动态组件的过程中,我想添加一个由创建者定义的参数
  • 子进程中的onClick事件应使用从动态组件的创建者获取的参数调用父进程中的onClick函数

对于代码:这是动态组件创建者和父级

  import React from 'react';

  // This is the creator of my dynamic components
  // It currently sets this.props.name as parameter for the parent function

  class CreateComponent extends React.Component {
    render(){
      return(
        <div className="childBox">
           // this.props.component is a react component of type ImageBox (see next code block)
          {React.cloneElement(this.props.component, {
            open: this.props.open(this.props.name),
            close: this.props.close,
          })}
        </div>
      )
    }
  }

  // This is the parent component, using the creator and some state to open/close different components
  export class DynamicContentGrid extends React.Component {
    constructor() {
      super();
      this.state = { activeComponent: '' };
    }

    close() {
      this.setState({ activeComponent: '' });
    }

    open(component) {
      this.setState({ activeComponent: component })
    }

    render() {
      console.log(this.props.children);
      return(
        <div className={css(styles.grid)}>
          <div className={css(styles.boxUpperLeft, styles.box)}>
            <CreateComponent
              component={this.props.children['upperLeft']}
              name='upperLeft'
              open={() => (name) => this.open(name)}
              close={() => this.close()}
            />
          </div>
        </div>
      )
    }
  }


  export default DynamicContentGrid;

这里是使用this.props.close而没有参数的非常基本的子组件(它们应该在创建者中设置):

import React from 'react';
export class ImageBox extends React.Component {
  render() {
    const {title, link, img} = this.props.content.front;
    return(
          <div>
            <h1>{title}</h1>
            <h2 onClick={this.props.open}>{link}</h2>
            <img src={img} />
          </div>
     )
  }
}

export default ImageBox;

什么有效

子组件的动态呈现工作正常。

它破裂的地方

如你所见,魔术发生在open={() => (name) => this.open(name)}。我想要的是:将this.open传递给创建者,将open(name)设置为参数,并将open函数传递给子节点。

一切正常,如果我直接在父母中说“name”参数,但由于几个原因我不想这样做。所以我需要一些讨论,但我无法弄清楚,出了什么问题。此时参数“name”未在创建者中正确设置。

javascript reactjs currying
1个回答
0
投票

在CreateComponent中设置open: () => this.props.open(this.props.name)

另外,删除() => (name) => this.open(name)并替换为this.open并将this.open = this.open.bind(this);放入构造函数中。

© www.soinside.com 2019 - 2024. All rights reserved.