React.js的新手。
我的代码很简单,但是App.js文件中有很多重复和硬编码的数字。
我将如何消除冗余?与/或 我如何摆脱硬编码的数字?
App.js
import React, { Component } from "react";
import Layout from "./components/Layout";
import one from "./components/img/one.jpg";
import two from "./components/img/two.jpg";
import three from "./components/img/three.jpg";
class App extends Component {
state = {
title: ["Monsoon III", "Beans", "Move 2"],
description:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent at
magna sed nunc venenatis congue nec non dui. Maecenas efficitur luctus
tellus sed volutpat. Sed egestas tortor id erat sollicitudin, vehicula
gravida nulla facilisis. Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Praesent in velit sem. Maecenas pellentesque
scelerisque mauris, ac lobortis neque laoreet et. In tristique tellus
sed ante venenatis fermentum. Mauris sed libero augue."
};
render() {
return (
<div>
<Layout
type={true}
img={one}
title={this.state.title[0]}
description={this.state.description}
/>
<Layout
type={false}
img={two}
title={this.state.title[1]}
description={this.state.description}
/>
<Layout
type={true}
img={three}
title={this.state.title[2]}
description={this.state.description}
/>
</div>
);
}
}
export default App;
Layout.js
import React, { Component } from "react";
class layout extends Component {
layoutType() {
//if true return the first layout type
if (this.props.type) {
return (
<div>
<img src={this.props.img} />
<p>
<h1>{this.props.title}</h1>
{this.props.description}
</p>
</div>
);
}
//else return the second layout type
return (
<div>
<p>
<h1>{this.props.title}</h1>
{this.props.description}
</p>
<img src={this.props.img} />
</div>
);
}
render() {
return <div>{this.layoutType()}</div>;
}
}
export default layout;
再次
我将如何消除冗余?与/或 我如何摆脱硬编码的数字?
答案 0 :(得分:1)
我认为可以将硬编码的号码重构为list
render() {
const { title, description } = this.state
const imgs = [one, two, three]
const Layouts = title.map((item,index) => {
return (
<Layout
type={false}
img={imgs[index]}
title={item}
description={description}
/>
)
})
return Layouts
}