所以我正在尝试使用 react js 制作一个博客应用程序。我正在使用 map 函数来显示所有提要(我使用 axios 获取)。我将这些提要存储在状态中并将它们作为props传递。现在的问题是:我试图在 map 函数中使用 bootstrap modals 来在单击按钮时显示博客的内容。我将模态存储在单独的组件中。但是,当我单击按钮时,由于地图功能,它会遍历所有元素并为 modal 内页面中的每个元素显示最后输入的数据(博客内容)。
Feed.jsx:
class Feed extends Component {
constructor(props) {
super(props);
this.state = {
showModal: false,
modalId: null
};
}
showModal = (e, index) => {
this.setState({ showModal: true, modalId: index });
console.log("Index: " + index);
};
hideModal = (e, index) => {
this.setState({ showModal: false, modalId: index });
console.log("Index: " + index);
};
disp(e) {
console.log("function: " + e._id);
}
showArticle(e) {}
render() {
let modalClose = () => this.setState({ showModal: false });
return (
<div className="container-fluid">
<ul className="list-group" key={this.props.feedData.id}>
{this.props.feedData.map(feed => (
<li
className="list-group-item"
style={styles.container}
key={feed.id}
>
<div className="container">
<div className="col-md-12">
<button
type="button"
className="btn btn-default"
onClick={() => this.setState({ showModal: true })}
>
<h3 style={styles.heading}>{feed.title} </h3>
</button>
<p>by - {feed.author}</p>
<p>{feed.subTitle}</p>
<div>
<span className="badge">Posted {feed.date}</span>
<div className="pull-right">
<button className="btn btn-primary">Upvote</button>{" "}
<button className="btn btn-info">Comment</button>{" "}
<button className="btn btn-danger">Report</button>{" "}
</div>
</div>
<br />
<Article
show={this.state.showModal}
onHide={modalClose}
data={feed}
/>
{this.disp(feed)}
</div>
<hr />
</div>
</li>
))}
</ul>
</div>
);
}
}
文章.jsx
class Article extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
console.log("Data from Article.jsx: " + this.props.data.title);
return (
<div className="article">
<Modal
{...this.props}
size="lg"
aria-labelledby="contained-modal-title-vcenter"
centered
>
<Modal.Header closeButton>
<Modal.Title id="contained-modal-title-vcenter">
{this.props.data.title}
</Modal.Title>
</Modal.Header>
<Modal.Body>
<h4> {this.props.data.subTitle} </h4>
<p>{this.props.data.content}</p>
</Modal.Body>
<Modal.Footer>
<Button onClick={this.props.onHide}>Close</Button>
</Modal.Footer>
</Modal>
</div>
);
}
}
我从父组件获取 feedData,该组件的提要存储在 fetch api 的状态中。安慰:
The development server has disconnected.
Refresh the page if necessary. webpackHotDevClient.js:65
function: 5cf24b53431f5f089496354b Feed.jsx:25
function: 5cf7a4b26332500efc0d1919 Feed.jsx:25
function: 5cfb558d9198991ea00a9452 Feed.jsx:25
Data from Article.jsx: Liberalism and Loyality Article.jsx:10
Data from Article.jsx: Made my first website Article.jsx:10
Data from Article.jsx: IOT project for tracking heart beat and monitoring data on phone.
如何使用模态渲染单个提要?