0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JSXの基本

Last updated at Posted at 2019-07-02

JSXとは

  • JavaScriptの拡張⾔語
  • 実行時に、JavaScriptにトランスコンパイル(変換)される。
  • (React.createElementメソッドに変換される)

例えば、このファイルの場合

index.js
const titleName = 'New Homepage';

const tag = (
 <div className="main">
 <h1>This web site is {titleName}</h1>
 <img src="http://~" />
 </div>
);

このように変換される

index.js
const name = 'New Homepage';

const tag = React.createElement(
 'div',
 { className: 'main' },

 React.createElement(
  'h1',
  null,
  `This web site is ${titleName}`
 ),
 React.createElement(
  'img',
  { src: 'http://~' }
 ),
);

基本的なルール

 ルート要素

index.js

ReactDOM.render(
 <h1>React</h1>
 <a>about</a>
 <a>jsx</a>
 document.getElementById('root')
);

上のように、複数の要素を並べることはできない
以下のように唯一のルート要素を持つようにする

index.js

ReactDOM.render(
 <div>
  <h1>React</h1>
  <a>about</a>
  <a>jsx</a>
 </div>,
 document.getElementById('root')
);

<div>を出力したくない場合、仮の要素として<React.Fragment>を使えば、出力されない

index.js

ReactDOM.render(
 <React.Fragment>
  <h1>React</h1>
  <a>about</a>
  <a>jsx</a>
 </React.Fragment>,
 document.getElementById('root')
);

空要素は/>で終える

const tag = <img src={logo}>;

const tag = <img src={logo} />;

属性

classclassName
forhtmlFor
tabindextabIndex (キャメルケースにする)

コメント

<!-- コメント -->

{/*コメント*/}

タグの中に書く場合
<p // コメントです。 >
<p /* コメント */ >

JavaScript式に埋め込む

index.js
const name = 'jon';

ReactDOM.render(
 <p>hello, {name}</p>,
 document.getElementById('root')
);

演算子、関数の呼び出しも可能

index.js
ReactDOM.render(
 <div>
  <p>{ 'hello, ' + name + '!' }</p>
  <p>Date: { new Date().toLocaleString() }</p>
  <p>2 * 330 + 6 = { 2 * 330 + 6 }</p>
 </div>,
 document.getElementById('root')
);
const url = 'https://~';
ReactDOM.render(
 <a href={url}>web page</a>,
 document.getElementById('root')
);

css属性

const style = { color: '#000', backgroundColor: '#fff' };
//キャメルケースを使うことに注意

ReactDOM.render(
 <p style={style}>WINGSプロジェクト</p>,
 document.getElementById('root')
);

タグの属性をまとめて指定

...演算⼦を利⽤することで、複数の属性をまとめて指定できる

const attrs = {
 src: 'http://~',
 alt: '',
 title: 'web page'
};

ReactDOM.render(
 <img {...attrs} />,
 document.getElementById('root')
);

<img src="http://~" alt="" title="web page">

参照
https://ja.reactjs.org/docs/jsx-in-depth.html#___gatsby

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?