这些天,我开始学习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>;
}
}
children
中调用props
export default class NodeContainer extends Component {
render() {
return <div className="node-container">{this.props.children}</div>;
}
}
您的问题是,您将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
中来实现相同的目的。