JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>React Test</title>
</head>
<body>
<!-- CDNを使えば、ローカルにダウンロードしなくてよい -->
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.10.3/babel.min.js"></script>
<h1>らくらくお買い物♪</h1>
<!--<div id="area_calc"></div>-->
<div id="area_calc"></div>
<script type="text/babel" src="/js/calculator.js"></script>
<script type="text/babel">
/* 生成したコードをindex.htmlの#area_calcに出力 */
ReactDOM.render(
<div>
<MyCalc name="メロン" price={540} />
<MyCalc name="いちご" price={500} />
<MyCalc name="バナナ" price={440} />
</div>,
document.getElementById('area_calc')
);
</script>
</body>
</html>
Babel + JSX
class MyCalc extends React.Component {
constructor(props) {
super(props);
this.state = {
item_quantity: 0,
item_amount: 0
}
// ES6は明示的にbindしてあげる必要がある
this.setQuantity = this.setQuantity.bind(this);
this.calcMultiple = this.calcMultiple.bind(this);
}
setQuantity =(event)=> {
this.setState({
item_quantity: event.target.value
});
}
calcMultiple =()=> {
let amount = this.props.price * this.state.item_quantity;
this.setState({
item_amount: amount
});
}
render() {
return (
<p>
<span>{this.props.name} : {this.props.price}円 x </span>
<input type="text" name="count" onChange={this.setQuantity}/>個
<button onClick={this.calcMultiple}> 【計算する】 </button>
<span>{this.state.item_amount}</span>円
</p>
);
}
}