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.

React初心者覚書01 - hello react -

0
Last updated at Posted at 2020-07-23

JSもままならない人(初級の中くらい)が、Reactをなんとか理解しようとしてみる試みです。初心者が理解できない例として捉えていただけたらと思います。

  • 数年前からたまにやってみようとして何度か挫折し、読んだこともすぐに忘れるので、覚書を書いてみることにしました。
    その際に、何がわからないかも()で併記していきます。根本的に理解できていないので、もし何かコメントをいただけるとありがたいです。

基本的にはReactの日本語サイトを見て、覚書を書いていきます。

Reactとは

(出来たものを見ると便利そうだが、何なのか理解できていない)

  • インタラクティブな UI の作成
  • 宣言的なViewを用いる(そもそもViewが何なのかよくわかっていない)
  • コンポーネントベース(パーツを作って組み合わせる?具体的に何なのかわからない)

一番短い例
 - React DOMが React要素に合致するようにDOMを更新する作業を担当している>UIを更新する唯一の方法

ReactDOM.render(要素, 書き出す場所);

hello.js
ReactDOM.render(
  <h1>Hello,world!<?h1>,
  document.getElementById('root')
);
hello02.html
<div id="root"></div>
hello02.js
const element = <h1>Hello, world</h1>;
ReactDOM.render(element,document.getElementById('root'));
  • React DOM は要素とその子要素を以前のものと比較し、DOM を望ましい状態へと変えるのに必要なだけの DOM の更新を行

JSXとは(なんとなく理解)

  • JSの構文の拡張
  • CSSに見えるが JSのオブジェクト

コンポーネント

  • JSの関数と似ている。 propsからの任意の入力を受け取り、画面上にReact要素として返す。
  • コンポーネント定義で一番簡単なのは、JSの関数
    - 下記の2つcomp01.jsとcomp02.jsは等価(よくわからない)
comp01.js
function Welcome(props{
return <h1>Hello, {props.name}</h1>;
}
comp02.js
class Welcome extends React.Component{
render(){
return <h1>Hello,{this.props.name}</h1>;
}
}

コンポーネントのレンダー

  • コンポーネント名は常に大文字で始める
comp-render.js
const element = <Welcome name="Hanako" />;

ここが多分自分がつまづく部分で、何がわからないかと言うと、
element変数になぜ、Welcome関数を持ってきているのかがわからない。なぜわざわざ?と思ってしまう(普通のプログラマだとすぐわかると思いますが、お許しを)。自分だと自分の誤ったコード.jsのようにしたくなる。

自分の誤ったコード.js
function Welcome(props) {
  return <h1>Hello, Hanako</h1>;
}
 ReactDOM.render(
Welcome,
document.getElementById('root')
);
comp-render02.js 正しい
function Welcome(props){
return <h1>Hello, {props.name)</h1>;
}

const element = <Welcome name = "Hanako" />;

ReactDOM.render(
element,
document.getElementById('root')
);

でも、次の例を見て、なんとなく理解、、

コンポーネント組み合わせ.js
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

function App() {
  return (
    <div>
      <Welcome name="Sara" />
      <Welcome name="Cahal" />
      <Welcome name="Edite" />
    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
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?