1 回答
TA贡献1868条经验 获得超4个赞
好的,所以我修复了你的代码,我会评论我所做的一切。
// periodicTable doesn't need to be part of the PeriodicTable Component, Juan Marco has made a good sugestion to stract it to a JSON
// for now I'll just put it in a variable outside PeriodicTable
const periodicTable = [
// 1 row
{
blank: false,
name: "hydrogen",
short: "H",
z: 1,
mass: 1.006,
},
{
blank: true
},
{
blank: true
},
{
blank:true
},
{
blank: true
},
{
blank: true
},
{
blank: true
},
{
blank: true
},
{
blank: true
},
{
blank: true
},
{
blank: true
},
{
blank: true
},
{
blank: true
},
{
blank: true
},
{
blank: true
},
{
blank: true
},
{
blank: true
},
{
blank: false,
name: "hellium",
short: "He",
z: 2,
mass: 4.0026,
},
// 2 row
];
// I've created a new Component that will handle the elements rendering, it's just a Function Component
function TableElement(props) {
const { elementData } = props;
const { blank, z, short, mass } = elementData;
if (blank) return <div className="periodicCard blank" />; // take note that in JSX files, HTML classes are className
return (
<div className="periodicCard">
<sup className="periodicZ">{z}</sup>
<div className='center'>
<strong className="periodicElement">{short}</strong>
</div>
<div className='center'>
<p className="periodicMass">{mass}</p>
</div>
</div>
);
}
class PeriodicTable extends React.Component {
constructor(props) {
super(props);
this.state = {
show: true,
};
}
// React knows how to handle arrays of ReactComponents, but you must put a key in each element of the array
generatePeriodicTable = () => {
return periodicTable.map((el, i) => <TableElement elementData={el} key={i} />);
}
showLearnItPage = () => {
this.setState({ show: false });
}
render() {
if(this.state.show) {
return (
<div>
<h2>Periodic<sup className="sup">table</sup></h2>
<main className="biggrid">
{this.generatePeriodicTable()}
</main>
<div className='center'>
<button className='periodic-table-page-button' onClick={this.showLearnItPage}>Back</button>
</div>
</div>
);
}
// after an if with a return you don't need to use else
return <LearnItPage />;
}
}
export default PeriodicTable;
现在一切都应该按您的预期工作。花一些时间阅读React 教程。
添加回答
举报