[在React JavaScript中,如何在另一个类中调用一个类? (下面的详细信息)

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

这些天,我开始学习JavaScript并做出反应,我试图在网站上绘制一些网格并遇到这样的问题:

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

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
      </>
    );
  }
}

网格只是消失了,什么都没有: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>;
  }
}
javascript reactjs class grid components
1个回答
0
投票
为此,您需要在children中调用props

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


0
投票
我看不到Node类的引用位置,所以不确定是否相关。

您的问题是,您将nodes组件传递给NodeContainer组件,而不是在NodeContainer中将它传递给[[rendering。您应该研究如何将props传递给组件-它们在组件上显示为this.props.children。您的代码应如下所示。

export default class NodeContainer extends Component { render() { return <div className="node-container">{this.props.children}</div>; } } [如果您想知道nodes如何显示为this.props.children,那是因为React处理组件的方式。您可以通过将它作为道具显式传递到children中来实现相同的目的。

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