Как динамически передавать реквизиты и их методы компоненту в React? - PullRequest
0 голосов
/ 04 октября 2018

У меня есть родительский компонент, который динамически загружает дочерние компоненты:

Родительский компонент:

// ... lifecycle methods et al

   setOverviewRef(ref) {
    this.OverviewHeader = ref;
  }

  setBowSizeCompareRef(ref) {
    this.bowSizeCompare = ref;
  }

  setDualVideoRef(ref) {
    this.dualVideoRef = ref;
  }

render() {

    const showComponent = (componentName, {refToPass, refMethod}) => {
      if (typeof this.state[`${componentName}`] !== undefined && this.state[`${componentName}`] !== null) {
        const Component = this.state[`${componentName}`].default;
        console.log('{refToPass, refMethod}: ', {refToPass, refMethod});
        return (
          <Component {...{ refToPass: this[`${refMethod}`] }} />
        );
      } else {
        return null;
      }
    }

    return (
      <section>
        <OverviewHeader overviewRef={this.setOverviewRef} />
        { showComponent('BowSizeCompareComponent', {refToPass: 'bowSizeCompareRef', refMethod: 'setBowSizeCompareRef' }) }
        { showComponent('DualVideoComponent', {refToPass: 'dualVideoRef', refMethod: 'setDualVideoRef' }) }
      </section>
    );
  }

Предполагая, что я хочу BowSizeCompareComponent, как мне получить его, чтобы Componentвозвращается из showComponent в форме:

<Component bowSizeCompareRef={this.setBowSizeCompareRef} />

Если это было DualVideoComponent, должно быть в форме:

<Component dualVideoRef={this.setDualVideoRef} />

1 Ответ

0 голосов
/ 05 октября 2018

Мне нужно было исправить структуру переданного в refObj в showComponent():

render() {

    const showComponent = (componentName, refObj) => {
      if (typeof this.state[componentName] !== undefined && this.state[componentName] !== null) {
    const Component = this.state[componentName].default;
    return (
      <Component {...refObj} />
    );
  } else {
    return null;
  }
};

    return (
      <section>
        <OverviewHeader overviewRef={this.setOverviewRef} />
        { showComponent('BowSizeCompareComponent', {bowSizeCompareRef: this.setBowSizeCompareRef }) }
        { showComponent('DualVideoComponent', {dualVideoRef: this.setDualVideoRef }) }
      </section>
    );
  }
...