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..
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745254418a4618868.html
评论列表(0条)