[React] React Fundamentals: Build a JSX Live Compiler

时间:2021-12-25 04:19:59

we want to have the ability to write JSX and see the output live in the browser.

<!doctype html>
<html lang="en">
<head>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="style.css"/>
<script src="//fb.me/react-0.13.3.js"></script>
<script src="//fb.me/JSXTransformer-0.13.3.js"></script>
<meta charset="utf-8">
<title>Compiler</title>
</head>
<body>
<script type="text/jsx">
/** @jsx React.DOM */ var App = React.createClass({
getInitialState: function() {
return {
input: '',
output: '',
err: ''
}
},
update: function(e) {
try{
var input = this.refs.htmlCode.getDOMNode().value;
this.setState({
output: JSXTransformer.transform(input).code,
err: ''
})
}catch(err){
this.setState({
err: err.message
})
}
},
render: function() {
return (
<div className="container">
<div className="row">
<div className="alert alert-danger">
&nbsp;{this.state.err}
</div>
</div>
<div className="row">
<textarea type="text" className="col-md-6 input-lg"
ref="htmlCode"
defaultValue={this.state.input} onChange={this.update}></textarea>
<pre className="col-md-6 input-lg">{this.state.output}</pre>
</div>
</div>
)
}
}); React.render(<App />, document.body);
</script>
</body>
</html>