这几天开始学习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
</>
);
}
}
网站结果是这样的,这很好:
但是当我像这样更改代码时:
render() {
const { nodes } = this.state;
console.log(nodes);
return (
<>
<p style={{ fontSize: 40 }}>Visualize Algorithms</p>
<br />
<br />
<NodeContainer>{nodes}</NodeContainer> // HERE
</>
);
}
}
网格就消失了,<body>
中什么也没有。 :
有人可以帮我吗?我不明白为什么会发生这种情况。
类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/