快速尝试 JSX
在项目中尝试 JSX 最快的方法是在页面中添加这个 <script>
标签:
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
现在,你可以在任何 <script>
标签内使用 JSX,方法是在为其添加 type="text/babel"
属性。这是一个使用了 JSX 的 HTML 文件的例子,你可以下载并尝试使用。
使用jsx和不使用jsx的区别:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>在网站中添加 React</title> <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> <!-- Don't use this in production:使用jsx语法需要引入babel --> <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> </head> <body> <div id="root"></div> <script type="text/babel"> class Test extends React.Component { constructor(props) { super(props); this.state = { list: [1, 2, 3] } } componentWillMount() { console.log("componentWillMount:组件将要被挂载。"); } componentDidMount() { console.log("componentDidMount:组件完成挂载,此时组件已经显示在页面上。"); } componentWillReceiveProps() { console.log("componentWillReceiveProps:组件将要接受新的属性。"); } shouldComponentUpdate() { console.log("shouldComponentUpdate:组件是否需要进行更新。此时,组件尚未被更新。"); return true; } componentWillUpdate() { console.log("componentWillUpdate:组件将要被更新。"); } componentDidUpdate() { console.log("componentDidUpdate:此时页面被重新渲染。"); } componentWillUnmount() { console.log("componentWillUnmount:组件将要被卸载的时候。"); } render() { return ( <div id="app"> { this.state.list.map((ele, index) => { return <h1 key={index}>{ele}</h1> }) } </div> ) } }; ReactDOM.render( <Test />, document.getElementById('root') ); </script> <!-- Note: this page is a great way to try React but it's not suitable for production. It slowly compiles JSX with Babel in the browser and uses a large development build of React. Read this section for a production-ready setup with JSX: https://reactjs.org/docs/add-react-to-a-website.html#add-jsx-to-a-project In a larger project, you can use an integrated toolchain that includes JSX instead: https://reactjs.org/docs/create-a-new-react-app.html You can also use React without JSX, in which case you can remove Babel: https://reactjs.org/docs/react-without-jsx.html --> </body> </html>