I started to study ReactJS and can't understand the purpose of components. for instance lets have a component:
var QuoteMaker = React.createClass({
render: function () {
return (
<blockquote>
<p>
The world is full of objects, more or less interesting; I do not wish to add any more.
</p>
<cite>
<a target="_blank"
href="#">
Douglas Huebler
</a>
</cite>
</blockquote>
);}});
why can't we just use
var thisVar = (
<blockquote>
<p>
The world is full of objects, more or less interesting; I do not wish to add any more.
</p>
<cite>
<a target="_blank"
href="#">
Douglas Huebler
</a>
</cite>
</blockquote>
)
instead of that component.
React allow you to get a composant approach. So you can use as a new balise text (composant) in react. You can reuse this component, it will have the same behavior everywhere.
You could. That would be just fine.
What you couldn't do is have a list of those, built from dynamic data. What if you wanted multiple quotes from multiple people?
What if you wanted a button that randomized which quote appeared?
What if you wanted a twitter feed, or a blog roll, or a comment section?
You don't necessarily need the createClass
. That's a particularly old way of looking at things, and you should really be using a Babel build pipeline; full stop.
You can simply say:
const Quote = (props) => (
<blockquote>
<p>{ props.quote }</p>
<cite >{ props.author }</cite>
</blockquote>
);
ReactDOM.render(<Quote quote="..." author="..." />, rootEl);
Now you can happily build a randomizer, or a quote API, or a quote editor, or whatever. The component does what it should, and it leans on input from the outside world for what it shouldn't do.
That way that you have in example can be created function, or stateless components, where we can use props
object, that can be passed from the parent object.
const Component = (props) => {
//access to props
}
Class components allows to store thier own state and use it to rerender the component, via this.setState()
function:
class Component extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
//access to both state and props
}
Why we must use components instead of js objects? Because react has its own DOM - virtual DOM
, where it listening to changes and rerendering your real DOM, you can reuse or extend this component anywhere and its also semanticly awesome.
Take a look to thedocumentation about React components.
There are lots of uses for components. These are few:
As i said before, there are lots of uses for components over flat html, and basically this is the whole point of ReactJS as component based :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.