ReactNative Day3

02-IntroToJSX.md 🔗

03-JsX Detail Url🔗

JSX

Remember we returned React.createElement from the function to tell React what the DOM should look like when we render this component. Another alternative way of telling React what the DOM should look like is by using JSX.
JSX is a very common and recommended way (preferred over React.createElement syntax in most cases) to write React code. The equivalent of return statement we saw in previous page (using React.createElement) in JSX would be:

return (
    <div>Hello World</div>
)

Although you write HTML looking syntax, your JSX code is compiled into a JavaScript function like the one we saw in the previous page. The above JSX code is compiled into:

return React.createElement('div', null, 'Hello World');

So writing above JSX code or React.createElement code will generate exactly same output on the browser. You can definitely write all your React code using React.createElement and not ever care about JSX. But it's gonna get pretty complicated pretty soon. Imagine writing all the nested React.createElement functions for generating simple HTML like below:

<table>
    <thead>
        <th>
            <td>Col</td>
        </th>
    </thead>
    <tbody>
        <tr>
            <td>Cell</td>
        </tr>
    </tbody>
</table>

You'd have to write something like this, which is not very pretty,可以这么写,但是很难看。:

React.createElement('table', null, 
    [
        React.createElement('thead', null, 
            React.createElement('th', null,
                React.createElement('td', null, 'Col')
            )
        ),
        React.createElement('tbody', null, 
            React.createElement('tr', null,
                React.createElement('td', 'null', 'Cell')
            )
        )
    ]

So in essence 本质上来说 JSX is nothing more than a syntactic sugar for complicated React.createElement functions to make React code more elegant and readable.提高优雅和可读性。

Tips

If you want to execute any JavaScript code within JSX then you surround your JavaScript code with curly braces { //JavaScript code } and put it anywhere in JSX. It will evaluate your code every time it renders the component to find out what it should render on the browser.

For example let's imagine we want to display a company profile information and a Company ticker. And imagine the Company ticker is stored on some variable somewhere and the company profile information is stored in another variable as an object. In that case we might write:

function CompanyProfile(props) {
    //ticker and companyProfileInfo stored in a variable
    const ticker = 'AAPL';
    const companyProfileInfo = {
        'Company Name': 'Apple Inc.',
        'Exchange': 'Nasdaq',
        'Sector': 'Technology',
        'Industry': 'Computer Hardware',
        'CEO': 'Timothy D. Cook'
    };
    return (
        <div>
            <div>Profile of: {ticker}</div>
            <div>
                {
                    {/*This is JavaScript code inside the curly braces*/}
                    Object.keys(companyProfileInfo)
                        .map((key, index) => {
                            return <div>{key}: {companyProfileInfo[key]}</div>
                        })
//In this case we mapped each key of the
// companyProfileInfo object to a div element. 
                }
            </div>
        </div>
    )
}

The HTML output of the above Component when it's rendered will be:

<div>
    <div>Profile of: AAPL</div>
    <div>
        <div>Company Name: Apple Inc.</div>
        <div>Exchange: Nasdaq</div>
        <div>Sector: Technology</div>
        <div>Industry: Computer Hardware</div>
        <div>CEO: Timothy D. Cook</div>
    </div>
</div>

Object.key指南

// simple array
var arr = ['a', 'b', 'c'];
console.log(Object.keys(arr)); // console: ['0', '1', '2']

// array like object
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']

// array like object with random key ordering
var anObj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.keys(anObj)); // console: ['2', '7', '100']

// getFoo is a property which isn't enumerable
var myObj = Object.create({}, {
  getFoo: {
    value: function () { return this.foo; }
  }
});
myObj.foo = 1;
console.log(Object.keys(myObj)); // console: ['foo']

Next is talking about the .map

const list = [ 'h', 'e', 'l', 'l', 'o'];
list.map((currElement, index) => {
  console.log("The current iteration is: " + index);
  console.log("The current element is: " + currElement);
  console.log("\n");
  return currElement; //equivalent to list[index]
});

Output is shown below:

The current iteration is: 0 <br>The current element is: h

The current iteration is: 1 <br>The current element is: e

The current iteration is: 2 <br>The current element is: l

The current iteration is: 3 <br>The current element is: l 

The current iteration is: 4 <br>The current element is: o

相当于循环遍历,It is fantastic.

JSX tag

In JSX, a component must return one and only one enclosing tag. That tag can have as many children as it wants.

// ❌ This is illegal in React since the return has more than one tag.
return ( 
    <div></div>
    <div></div>
)

// ✅ This is perfectly legal because there is just one enclosing tag and
// it can have as many children as it likes
return (
    <div>
        <div>
            <div></div>
        </div>
        <div></div>
    </div>
)

// ✅  If you don't want to wrap your component with some enclosing tag like `div`
// you can wrap everything with `React.Fragment` which is an empty tag provided by React
return (
    <React.Fragment>
        <div></div>
        <div></div>
    </React.Fragment>
)

Key takeaways:

  • Components must return only one tag. This tag can have as many children as it likes. Instead of a tag, it can however return a string or null.
  • You can run any JavaScript code inside the return using curly braces {//run any JavaScript}.
  • Outside of the return it's exactly like any other JavaScript class or function. You can do whatever you desire to do.

### Differences with HTML

There are some commonly used things that are slightly different in JSX than in HTML.

- Styles

In HTML, styles are passed as string. The css properties are kebab-cased.

```html
<div style="bottom-border: 1px solid green"></div>

In JSX, styles are passed as an object. The css properties are camelCased.

<div style={{ bottomBorder: `1px solid green`}}></div>
  • Class

In HTML class attribute is passed as string.

<div class="container"></div>

In JSX also class attribute is passed as string but instead of calling it class we call it className. That's because JSX is extension of JavaScript and "class" is a reserved keyword in JavaScript.

<div className={"container"}></div>
  • Event Handler

In HTML event handler attribute is all lower cased and the handlers are passed as string.

<div onclick="clickHandler()"></div>

In JSX, event handler are camelCased and instead of string we pass the actual function.

<div onClick={function(){ alert('clicked')}}></div>

We will look more into event handler later in the tutorial.

posted @ 2021-12-22 15:12  Indullged  阅读(24)  评论(0编辑  收藏  举报