admin管理员组文章数量:1416306
I read an article and the author critic below code, I wonder what's wrong with it. I was starting to learn React, too bad the author did not point out what's his problem with the code below. I tested the code below, it's running fine.
import React from 'react';
import './App.css';
const TodoItems = React.createClass({
getInitialState() {
return {
items : [
{id:1,name:"Gym"},
{id:2,name:"Jump"},
{id:3,name:"Racing"}
]
}
},
renderItem(){
return(
<ul>
{this.state.items.map((item,i) =>
<li key={i}>item.name</li>
)}
</ul>
)
},
render(){
return (
<renderItem />
)
}
})
ReactDOM.render(<TodoItems />,document.getElementById('app'));
I read an article and the author critic below code, I wonder what's wrong with it. I was starting to learn React, too bad the author did not point out what's his problem with the code below. I tested the code below, it's running fine.
import React from 'react';
import './App.css';
const TodoItems = React.createClass({
getInitialState() {
return {
items : [
{id:1,name:"Gym"},
{id:2,name:"Jump"},
{id:3,name:"Racing"}
]
}
},
renderItem(){
return(
<ul>
{this.state.items.map((item,i) =>
<li key={i}>item.name</li>
)}
</ul>
)
},
render(){
return (
<renderItem />
)
}
})
ReactDOM.render(<TodoItems />,document.getElementById('app'));
Share
Improve this question
asked Oct 2, 2016 at 12:48
Thian Kian PhinThian Kian Phin
9313 gold badges13 silver badges27 bronze badges
2 Answers
Reset to default 2The method renderItem should be outside as a functional or stateless ponent:
const RenderItem = (props) => {
return(
<ul>
{props.items.map((item,i) =>
<li key={i}>item.name</li>
)}
</ul>
)
};
The render method of the parent ponent should be:
render(){
return (
<RenderItem items={this.state.items} />
)
}
This is the standard way that we write React ponents. It causes maintainability issues when you write it that way.
In short, you code will not ensure ponent re-usability.
With React, you'll get the most of re-usability. In the above code, I can see that you are trying to render the items in the state in the function renderItem()
. The need of using functions
in any language is also to ensure re-usability. So, in React when you when you want to re-use a part which will return a HTML elements, make it as a separate ponent.
See the following fiddle https://jsfiddle/Pranesh456/b6v6fxrj/1/
Here, I made the renderItem()
as a separate ponent <RenderItem>
which can be reused in n
number of other ponents..
本文标签: javascriptrender array of object into a ltligt in reactjsStack Overflow
版权声明:本文标题:javascript - render array of object into a <li> in react.js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745254418a2650013.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论