普通页面引入React(使用和不使用JSX)

react

1. 不使用JSX

优点: 不用配置有关JSX的编译。

依赖语法:

React.createElement(component/type, props, ...chilidren);

//第一个参数可以是字符串,表示原始标签;

//也可以是React.Component的子类

html页面示例:

使用React的前提是引入react和react-dom文件;生产环境要使用production版本

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<meta http-equiv="X-UA-Compatible" content="ie=edge">

<title>Document</title>

</head>

<body>

<div id="like_button_container"></div>

<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>

<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>

<script src="./like_button.js"></script>

</body>

</html>

like_button.js

const e = React.createElement; // 简化代码

// LikeButton是一个React类组件

class LikeButton extends React.Component{

constructor(props) {

super(props);

this.state = {

liked: false

}

}

render() {

return e('button', {

onClick: () => {

this.setState({

liked: true

})

}

}, this.state.liked ? this.props.name : 'UnLike')

}

}

const domContainer1 = document.querySelector('#like_button_container');

// e(LikeButton)相当于e(LikeButton, undefined, undefined);

// type=Class, props={name: '1'}, children=undefined

ReactDOM.render(e(LikeButton, {name: '1'}), domContainer1);

2. 快速使用JSX

JSX元素本质上调用React.createElement方法。

注意: 该方法不适用于生产环境

html页面修改部分:

    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

<script src="./like_button.js" type="text/babel"></script>

首先,添加了babel文件,用于编译JSX语法;

其次, like_button.js文件必须添加类型type: "text/babel", 因为script标签默认"text/javascript"

修改类型后,文件请求默认修改成CORS请求。此时本地访问报跨域错误。因为CORS不支持FILE协议。

like_button.js修改

class LikeButton extends React.Component{

constructor(props) {

super(props);

this.state = {

liked: false

}

}

render() {

return (

<button onClick={() => { this.setState({ liked: true }) }}>

{this.state.liked ? this.props.name : 'UnLike'}

</button>

)

}

}

const domContainer1 = document.querySelector('#like_button_container');

ReactDOM.render(<LikeButton name="1" />, domContainer1);

3. 将JSX加入项目

可以用于生产环境的JSX配置环境。不需要手动引入babel。

html文件同1中html文件;js文件同2中js代码。

1. 安装JSX预处理器

1. 初始化项目

npm init -y

2. 安装babel和react预处理器

npm install babel-cli@6 babel-preset-react-app@3

2. 运行JSX预处理器

建一个文件夹,命名src; 将使用了JSX语法的like_button文件放入其中

运行下面的命令,启动一个JSX自动监听器,编辑源文件,会自动转化

npx babel --watch src --out-dir . --presets react-app/prod 

运行后,会在外面生成一个预处理过后的js文件,该文件处理后的文件也适用于旧浏览器。

  

以上是 普通页面引入React(使用和不使用JSX) 的全部内容, 来源链接: utcz.com/z/384013.html

回到顶部