ReactJS-如何从父级创建动态引用子是功能组件

时间:2019-03-08 22:39:50

标签: reactjs

这是孩子:

import React from 'react';

const Hero = (props) => (
  <div ref={props.heroRef} className={`hero-region ${props.class}`}>
    <h3>{props.copy}</h3>
  </div>
);

export default Hero;

这是父母:

import React, { Component, Fragment } from "react";
import Hero from "./../components/content/Hero";

export default class HomePage extends Component {
  render() {
    const createHeroNodes = () =>
      [
        { class: "light", copy: "first div" },
        { class: "dark", copy: "second div" }
      ].map((hero, i) => (
        <Hero
          heroRef={el => (this[`${heroRegion}${i}`] = el)}
          class={hero.class}
          copy={hero.copy}
        />
      ));

    return <Fragment>{createHeroNodes()}</Fragment>;
  }
}

我希望它创建像this.heroRegion1和this.heroRegion2这样可访问的子引用,以便在滚动时可以执行一些命令性动画。

我回来的是一个错误:“未定义heroRegion”

有什么想法吗?我试图避免将this.heroRegion1硬编码为this.heroRegion(... n)。

1 个答案:

答案 0 :(得分:1)

通过在模板文字中写入${heroRegion},您正试图访问heroRegion变量,该变量不存在。

您可以改写heroRegion${i},它将按预期工作。

示例

const Hero = props => (
  <div ref={props.heroRef} className={`hero-region ${props.class}`}>
    <h3>{props.copy}</h3>
  </div>
);

class HomePage extends React.Component {
  componentDidMount() {
    console.log(this.heroRegion0, this.heroRegion1);
  }

  render() {
    return (
      <React.Fragment>
        {[
          { class: "light", copy: "first div" },
          { class: "dark", copy: "second div" }
        ].map((hero, i) => (
          <Hero
            heroRef={el => (this[`heroRegion${i}`] = el)}
            class={hero.class}
            copy={hero.copy}
          />
        ))}
      </React.Fragment>
    );
  }
}

ReactDOM.render(<HomePage />, document.getElementById("root"));
<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="root"></div>