javascript - 在React JavaScript中,如何在另一个类中调用一个类?

标签 javascript reactjs class grid components

这几天开始学习JavaScript和React,我尝试在网站上画一些网格,遇到了这样的问题:

当我这样编码时一切正常:

export default class PathfindingVisualizer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      nodes: [],
    };
  }

  componentDidMount() {
    const nodes = getInitialGrid();
    this.setState({ nodes });
  }

  render() {
    const { nodes } = this.state;
    console.log(nodes);
    return (
      <>
        <p style={{ fontSize: 40 }}>Visualize Algorithms</p>
        <br />
        <br />
        <div className="node-container">{nodes}</div>  // HERE WORKS FINE
      </>
    );
  }
}

网站结果是这样的,这很好:

enter image description here

但是当我像这样更改代码时:

  render() {
    const { nodes } = this.state;
    console.log(nodes);
    return (
      <>
        <p style={{ fontSize: 40 }}>Visualize Algorithms</p>
        <br />
        <br />
        <NodeContainer>{nodes}</NodeContainer>  // HERE
      </>
    );
  }
}

网格就消失了,<body> 中什么也没有。 :

enter image description here

有人可以帮我吗?我不明白为什么会发生这种情况。

类NodeContainer和Node是这样的:

export default class NodeContainer extends Component {
  render() {
    return <div className="node-container"></div>;
  }
}
export default class Node extends Component {
  render() {
    return <div className="node-item"></div>;
  }
}


<小时/>


嘿,谢谢你们的回答:)这是我第一次在这里提问。我按照您所说的添加 {this.props.xxxxx} 解决了问题,并且它有效。 更正后的代码如下:

...
        <br />
        <br />
        <NodeContainer nodes={nodes}></NodeContainer> // HERE
      </>
...

NodeContainer 类:

export default class NodeContainer extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  render() {
    return <div className="node-container">{this.props.nodes}</div>; //HERE
  }
}

我没有使用“this.props.children”,但稍后会查看。我跳过了基本教程,所以我不明白如何将参数传递给类,我查看了这个视频来帮助自己快速理解这一点:
https://www.youtube.com/watch?v=ICmMVfKjEuo&list=PLN3n1USn4xlntqksY83W3997mmQPrUmqM&index=5&t=0s

最佳答案

为此,您需要在props中调用children

export default class NodeContainer extends Component {
  render() {
    return <div className="node-container">{this.props.children}</div>;
  }
}

关于javascript - 在React JavaScript中,如何在另一个类中调用一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61165153/

相关文章:

javascript - 更改链接悬停时的另一张图像

reactjs - 未捕获的类型错误 : exitFunction is not a function even though it is called successfully from another method

javascript - HOC 组件 - 数组返回 true 或 false

c++ - 根据 C++ 中的用户输入将不同的类分配给特定对象

javascript - nodejs v8.11.2 .foreach 不是函数错误

javascript - Chrome扩展中的POST请求数据和地址栏更改

javascript - 在现有 <div> 中定位动态内容的问题

对象属性的 Javascript 数组映射

java - 动态寻址类变量

C++ - 派生类中的 "Member function not declared"