こちらを参考にしました。
プロジェクトの作成
create-react-app re02
cd re02
yarn start
src/App.js を次で置き換えます。
src/App.js
import './App.css';
import React from 'react';
class Car extends React.Component {
constructor(props) {
super(props);
this.state = {
brand: "Ford",
model: "Mustang",
color: "red",
year: 1964
};
}
changeColor = () => { this.setState({color: "blue"}); }
changeGreen = () => { this.setState({color: "green"}); }
changeRed = () => { this.setState({color: "red"}); }
render() {
return (
<div>
<h1>My {this.state.brand}</h1>
<p>
It is a {this.state.color}
{this.state.model}
from {this.state.year}.
</p>
<button type="button" onClick={this.changeColor} >Change color</button>
<button type="button" onClick={this.changeGreen} >Change Green</button>
<button type="button" onClick={this.changeRed} >Change Red</button>
</div>
);
}
}
function App() {
return (
<div className="App">
<header className="App-header">
<p>Hello World!</p>
<Car />
<blockquote>
<p>Jun/28/2022</p>
</blockquote>
</header>
</div>
);
}
export default App;
ブラウザーで、 http://localhost:3000/ にアクセス