はじめに
タイトルの通りです。
React16 CDN でHelloWorld JSXありなし両方 - Qiita
https://qiita.com/standard-software/items/0cdbcdb2a6d6355c946b
上記記事の最新バージョンです。
先の記事では、HTMLファイル単独でした。今度はjsファイルを別にして開発します。
あとで書きますが、HTML ファイルと Jsファイルを別々にするので、Webサーバーを使って開発する必要があります。
ファイル
ファイルです。
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script src="./Button.js" type="text/babel"></script>
<script src="./Application.js" type="text/babel"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>
class Application extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 0,
}
this.onClick = this.onClick.bind(this);
}
onClick() {
let { counter } = this.state;
counter += 1;
this.setState({ counter });
}
render() {
return (
<div>
<span>{this.state.counter}</span>
<Button
onClick={this.onClick}
text={this.state.counter}
/>
</div>
);
}
}
ReactDOM.render(<Application />,
document.getElementById('root'));
class Button extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<button
onClick={this.props.onClick}
>
{this.props.text}
</button>
);
}
}
これらを同一フォルダに配置して、Webサーバー経由で起動してください。
すごく簡単ですが次のようなボタンを押すと、テキストとボタンテキストがカウントアップされるページが表示されます。
Webサーバーを起動するには次の記事などご参考ください。
ライブリロード(ファイル更新監視)してくれるWebサーバー browser-sync のはじめの一歩 - Qiita
https://qiita.com/standard-software/items/7a1d237133f0fe7961fd
node.js http-serverコマンドでwebサーバーを起動する - Qiita
https://qiita.com/standard-software/items/1afe7b64c4c644fdd9e4
ローカルファイルでブラウザ起動はできない
HTMLをローカルファイルとしてブラウザ起動だと次のようなエラーが出てしまうのでご注意ください。
jsファイルが他のサイトにあるから動かないよ、というエラーです。
画面はWindowsです。
Access to XMLHttpRequest at 'file:///C:/.../Button.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.
babel.min.js:1 GET file:///C:/.../Button.js net::ERR_FAILED
(anonymous) @ babel.min.js:1
yq @ babel.min.js:1
(anonymous) @ babel.min.js:1
Cq @ babel.min.js:1
kq @ babel.min.js:1
index.html:1 Access to XMLHttpRequest at 'file:///C:/.../Application.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.
babel.min.js:1 GET file:///C:/.../Application.js net::ERR_FAILED
JavaScriptコードがHTMLファイル内にかかれていれば、ローカルファイル起動でも動くのですが、jsファイルがHTMLファイルと別になっていると、ローカルファイル起動では動きません。
以上です。