منگل، 16 اگست، 2016
In this tutorial we will show you how to combine components to make the app easier to maintain. This approach will allow you to update and change your components without affecting the rest of the page.
Stateless Example
Our first component in example below isApp. This component is owner ofHeaderandContent. We are creatingHeaderandContentseparately and just adding it inside JSX tree in ourAppcomponent. OnlyAppcomponent needs to be exported.
App.jsx
importReactfrom'react';classAppextendsReact.Component{ render(){return( );}}classHeaderextendsReact.Component{ render(){return(Header
);}}classContentextendsReact.Component{ render(){return(Content
The content text!!!
);}}exportdefaultApp;
To be able to render this on page, we need to import it inmain.jsfile and callreactDOM.render(). We already did it when we were setting environment.
main.js
importReactfrom'react';importReactDOMfrom'react-dom';importAppfrom'./App.jsx';ReactDOM.render( , document.getElementById('app'));
Above code will generate following result:
Stateful Example
In this example we will set the state for owner component (App). TheHeadercomponent is just added like in the last example since it doesn't need any state. Instead of content tag, we are creatingtableandtbodyelements where we will dynamically insertTableRowfor every object from thedataarray. You can see that we are using EcmaScript 2015 arrow syntax (⇒) which looks much cleaner then the old JavaScript syntax. This will help us create our elements with fewer lines of code. It is especially useful when you need to create list with a lot of items.
App.jsx
importReactfrom'react';classAppextendsReact.Component{ constructor(){super();this.state ={ data:[{"id":1,"name":"Foo","age":"20"},{"id":2,"name":"Bar","age":"30"},{"id":3,"name":"Baz","age":"40"}]}}
render(){return({this.state.data.map((person, i)⇒)}
);}}classHeaderextendsReact.Component{ render(){return(Header
);}}classTableRowextendsReact.Component{ render(){return({this.props.data.id} {this.props.data.name} {this.props.data.age} );}}exportdefaultApp;
main.js
importReactfrom'react';importReactDOMfrom'react-dom';importAppfrom'./App.jsx';ReactDOM.render( , document.getElementById('app'));
NOTE
Notice that we are usingkey = {i}insidemap()function. This will help React to update only necessary elements instead of re-rendering entire list when something change. It is huge performance boost for larger number of dynamically created
Header
Content
The content text!!!
Header
سبسکرائب کریں در:
تبصرے شائع کریں (Atom)
کوئی تبصرے نہیں:
ایک تبصرہ شائع کریں