منگل، 16 اگست، 2016

React uses JSX for templating instead of regular JavaScript. It is not necessary to use it, but there are some pros that comes with it. JSX is faster because it performs optimization while compiling code to JavaScript. It is also type-safe and most of the errors can be caught during compilation. JSX makes it easier and faster to write templates if you are familiar with HTML. Using JSX JSX looks like regular HTML in most cases. We already used it in environment setup tutorial. Look at the code fromApp.jsxwhere we are returningdiv. App.jsx importReactfrom'react';classAppextendsReact.Component{ render(){return(
HelloWorld!!!
);}}exportdefaultApp; Even though it's similar to HTML, there are a couple of things you need to keep in mind when working with JSX. Nested Elements If you want to return more elements, you need to wrap it with one container element. Notice how we are usingdivas a wrapper forh1,h2andpelements. App.jsx importReactfrom'react';classAppextendsReact.Component{ render(){return(

Header

Content

Thisis the content!!!

);}}exportdefaultApp; Attributes You can use your own custom attributes in addition to regular HTML properties and attributes. When you want to add custom attribute, you need to usedata-prefix. In example below we addeddata-myattributeas an attribute ofpelement. importReactfrom'react';classAppextendsReact.Component{ render(){return(

Header

Content

Thisis the content!!!

);}}exportdefaultApp; JavaScript Expressions JavaScript expressions can be used inside of JSX. You just need to wrap it with curly brackets{}. Example below will render2. importReactfrom'react';classAppextendsReact.Component{ render(){return(

{1+1}

);}}exportdefaultApp; You can not useif elsestatements inside JSX but you can useconditional (ternary)expressions instead. In example below variableiequals to1so the browser will rendertrue, if we change it to some other value it will renderfalse. importReactfrom'react';classAppextendsReact.Component{ render(){var i =1;return(

{i ==1?'True!':'False'}

);}}exportdefaultApp; Styling React recommends using inline styles. When you want to set inline styles, you need to usecamelCasesyntax. React will also automatically appendpxafter the number value on specific elements. You can see below how to addmyStyleinline toh1element. importReactfrom'react';classAppextendsReact.Component{ render(){var myStyle ={ fontSize:100, color:'#FF0000'}return(

Header

);}}exportdefaultApp; Comments When writing comments you need to put curly brackets{}when you want to write comment within children section of a tag. It is good practice to always use{}when writing comments since you want to be consistent when writing the app. importReactfrom'react';classAppextendsReact.Component{ render(){return(

Header

{//End of the line Comment...}{/*Multi line comment...*/}
);}}exportdefaultApp


کوئی تبصرے نہیں:

ایک تبصرہ شائع کریں