【问题标题】:React - Component stored as variable not rendered in nested componentReact - 存储为变量的组件未在嵌套组件中呈现
【发布时间】:2020-04-13 19:32:43
【问题描述】:

我有以下组件:

信息显示器:

import React, { Component } from "react";
import Typing from "react-typing-animation";

import AnimeInfo from "./animeInfo";
import OtherInfo from "./otherInfo";

const infos = [AnimeInfo, OtherInfo];

export class InfoDisplayer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentIndex: 0,
    };

    this.updateDisplayedInfo = this.updateDisplayedInfo.bind(this);
  }

  updateDisplayedInfo = () => {
    const newState = {
      currentIndex: this.state.currentIndex,
    };
    if (this.state.currentIndex === infos.length - 1) {
      newState.currentIndex = 0;
    } else {
      newState.currentIndex++;
    }
    this.setState(newState);
  };

  render() {
    const Info = infos[this.state.currentIndex];
    return (
      <React.Fragment>
        <Info />
        <Typing onFinishedTyping={this.updateDisplayedInfo} loop>
          <Info />
          <Typing.Reset count={1} delay={2000} />
        </Typing>
      </React.Fragment>
    );
  }
}

export default InfoDisplayer;

动漫资讯:

import React, { Component } from "react";

export class AnimeInfo extends Component {
  render() {
    return <span>..watching anime</span>;
  }
}

export default AnimeInfo;

其他信息:

import React, { Component } from "react";

export class OtherInfo extends Component {
  render() {
    return <span>..simple test</span>;
  }
}
export default OtherInfo;

Info 通过循环进入infos 数组来检索。 (这工作正常,见React - Component is not re-rendered when state is changed

我已关注https://gist.github.com/sebmarkbage/f1f4ba40816e7d7848ad 将 Info 大写并确保它被正确地视为 JSX 组件。

打字组件来自https://github.com/notadamking/react-typing-animation

信息在打字外显示(和交换),但不在打字内。由于 Info 被交换,这意味着 updateDisplayedInfo 被调用,所以 Typing.onFinishedTyping 被触发。我不明白为什么Info 没有显示在Typing 中。 是图书馆相关的问题吗?

【问题讨论】:

  • 我想这可能是 Typing 组件的实际状态没有改变,它的内容也没有重新渲染。另外,当您无论如何都想更改状态时,将“循环”道具添加到 Typing 组件有什么意义。一种建议是删除循环道具并添加可能具有“this.state.currentIndex”作为值的关键道具。这将导致 Typing 组件在您更改 info 组件时始终重新渲染...

标签: javascript reactjs


【解决方案1】:

如果您查看库源代码,您就会明白为什么这不起作用。

The lib gets the text from node.props.children,因此您必须将一些文本直接传递给&lt;Info&gt; 组件以使其呈现。还有the text to be animated is passed back to that component,所以组件需要能够显示传递给它的孩子:

const Info = ({children}) => {
  return (
    <h1>{children}</h1>
  )
}


<Typing>
  <Info>
    this is `props.children`
  </Info>
</Typing>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    • 2021-11-28
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多