React Intro

Source: React新手指南

1 L09

1.1 Each component must return a root element

1.1.1 usa a <div></div>

MyComp01.jsx
export default function MyComp01() {
  return (
    <div>
      <h1>Hello, this is oat!</h1>
    </div>
  );
}

1.1.2 use an empty element <></>

MyComp01.jsx
export default function MyComp01() {
  return (
    <>
      <h1>Hello, this is oat!</h1>
    </>
  );
}

…which is the same as using <Fragment>

MyComp01.jsx
import {Fragment} from 'react';

export default function MyComp01() {
  return (
    <Fragment> 
      <h1>Hello, this is oat!</h1>
    <Fragment/>
  );
}

1.2 Expression

  • Value of a variable can called in both the 1) contents, and 2) properties of an element as an expression, i.e., enclosed in {}

  • expression carries dynamic data , especially those passing to the component from outside.

MyComp01.jsx
let a = 10;
const button_name = "b1";

export default function MyComp01() {
  return (
    <div>
      <h1>Hello, value of a is {a}</h1>
      <button id={button_name}>
        click me: {button_name === "b1" ? "b1" : "wrong!"}
      </button>
    </div>
  );
}
1
used in content
2
used in property
3
conditional expression used in content

1.3 Naming conventions of properties

  • class -> className

  • for -> htmlFor

  • style must be specified as objects, as shown below:

html
<h1 style="height: 100px; color: blue; font-size: 20px"></h1>
jsx
export default function MyComp01() {
  return (
    <div>
    <h1 style={{
        height: '100px',
        color: 'blue',
        fontSize: '20px',
    }}>
        Hello
    </h1>
    </div>
  );
}

1.4 render by expression

let a = 10;

export default function MyComp01() {
  return (
    <div>
    { a === 10 ? <h1>a is 10</h1> : <button>a is not 10</button> } 
    </div>
  );
}

1.5 render by an array

Note

A unique key must be provided to each element in the array.

const arr = [
    <h1 key={1}>aaa</h1>
    <h1 key={2}>bbb</h1>
    <h1 key={3}>ccc</h1>
]

export default function MyComp01() {
  return (
    <div> { arr } </div>
  );
}

1.6 event binding

export default function MyComp01() {
  return (
    <div>
        <button onClick={ () => alert('warning!') }>click me!</button>
    </div>
  );
}
Back to top