我对 React 数组有点迷失了。我想要做的是拥有组件(文章)数组,并且在该数组中我想要拥有标题和内容。
我想要对该数组执行的操作是添加、删除并将其显示在我的页面上。
那我做错了什么?另外这个 Action 到底叫什么?
代码来自ReactJS demos并由我修改了一点。
var ReactDOM = require('react-dom');
var React = require('react');
// Articles page
const Articles = React.createClass({
getInitialState() {
return {article: [
{'title': 'hello', 'content': 'hello hello'},
{'title': 'hello1', 'content': 'hello hello1'},
{'title': 'hello2', 'content': 'hello hello2'},
{'title': 'hello3', 'content': 'hello hello3'}
]};
},
onAdd() {
const newArticle =
this.state.article.concat([window.prompt('Enter article')]);
this.setState({article: newArticle});
},
onRemove(i) {
const newArticle = this.state.article;
newArticle.splice(i, 1);
this.setState({article: newArticle});
},
render() {
const article = this.state.article.map((article, i) => {
return (
<div key={article} onClick={this.onRemove.bind(this, i)}>
{article}
</div>
);
});
return (
<div className="container">
<div className="row">
<div className="col-md-12 cBusiness">
<p>Articles Page</p>
<button onClick={this.onAdd}>Add Article</button>
<br />
<br />
{title}
<br />
<br />
{content}
</div>
</div>
</div>
);
},
});
module.exports = Articles;
最佳答案
在您的渲染方法中,没有变量title
和content
,但是有变量article
,您可以在其中创建包含文章的列表,您应从 render
中删除变量 title
和 content
并使用 article
。我重构了你的代码,现在看起来像这样
const Articles = React.createClass({
getInitialState() {
return {
articles: [
{'title': 'hello', 'content': 'hello hello'},
{'title': 'hello1', 'content': 'hello hello1'},
{'title': 'hello2', 'content': 'hello hello2'},
{'title': 'hello3', 'content': 'hello hello3'}
]
};
},
onAdd() {
const title = window.prompt('Enter article title');
const content = window.prompt('Enter article content');
this.setState({
articles: this.state.articles.concat({ title, content })
});
},
onRemove(index) {
this.setState({
articles: this.state.articles.filter((e, i) => i !== index)
});
},
render() {
const articles = this.state.articles.map((article, i) => {
return (
<div key={i}>
<h2>
{ article.title }
<span
className="link"
onClick={ this.onRemove.bind(this, i) }
>
X
</span>
</h2>
<p>{ article.content }</p>
</div>
);
});
return (
<div className="container">
<div className="row">
<div className="col-md-12 cBusiness">
<p>Articles Page</p>
<div>{ articles }</div>
<button onClick={this.onAdd}>Add Article</button>
</div>
</div>
</div>
);
},
});
关于arrays - 将组件推送到组件数组 - ReactJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35812562/