02 JSX学习

JSX介绍

JSX是JavaScript XML(HTML)的缩写,表示js代码书写HTML结构

作用:在react中创建HTML结构(界面UI结构)

例如:App.js中

function App() {
  return (
    <div className="App">
     app 
    </div>
  );
}

export default App;

jsx表示:

		(
    <div className="App">
     app 
    </div>
  )

​ 优势:

  • 采用类似HTML的语法,降低学习成本,会HTML就会JSX
  • 充分利用js自身的可编程能力创建HTML结构

注意:JSX并不是标准的JS语法,是JS的语法扩展,浏览器默认是不识别的,脚手架内置的@babel/plugin-transform-react-jsx包,用于解析改语法

左边是自己写的JSX语法,但是都会被变成一个一个函数的执行成JS语法

JSX使用js表达式

语法:

{ JS表达式}

例如:

// 1,识别常规的变量
const name = "fujiahao"

// 2,原生js方法i奥永
const getAgw = ()=>{
  return 18
}

// 3,三元运算符(常用)
const flag = true

// 4,字符串拼接
const str1 = 'demo'
const str2 = '2'

// 5,字符串切割
const str3 = 'abcbd'

// 6,拼接
const arr3 = ['a','b']

function App() {
  return (
    <div className="App">
     <h1>{name}</h1>
     <h1>{getAgw()}</h1>
     <h1>{flag? '真的':'假的'}</h1>
     <h1>{str1+str2}</h1>
     <h1> {str3.split('b')}</h1>
     <h1>{arr3.join(',')}</h1>
    </div>
  );
}

结果:

在这里插入图片描述

if语句/switch-case语句/变量声明语句,这些都是语句,不是表达式,不能出现在 {} 中

JSX中实现列表渲染

// react如何完成列表渲染
// 技术方案:map
// 注意事项:遍历列表时,同样需要一个类型为number/string不可重复的key,提高diff性能
// key仅仅在内部使用,不会出现在真是的dom结构中

const demo = [
  {id:1,name:"demo1"},
  {id:2,name:"demo2"},
  {id:3,name:"demo3"}
]


function App() {
  return (
    <div className="App">
      <ul>
        {demo.map(test=><li key={test.id}>{test.name}</li>)}
      </ul>
    </div>
  );
}

在这里插入图片描述

JSX条件渲染

// 条件渲染
// 技术方案:三元表达式,逻辑与运算

const flag = true

function App() {
  return (
    <div className="App">
     {flag?<span>this is span</span>:null}
     {flag?(<div>
      <h1>this is one span</h1>
      <h1>this is two span</h1>
      <h1>this is three span</h1>
     </div>):null}

     {true&& <span>this is true span</span>}
     {false&& <span>this is false span</span>}
    </div>
  );
}

JSX模板精简原则

// 条件渲染
// 有一个状态type 1 2 3
// 1->h1
// 2->h2
// 3->h3

// 原则:模板中的逻辑尽量保持精简
// 复杂的分支逻辑,收敛为一个函数,通过一个专门的函数来写分支逻辑,模板之负责调用

const getHTag = (type)=>{
  if(type==1){
    return <h1>this is h1</h1>
  }
  if(type==2){
    return <h2>this is h2</h2>
  }
  if(type==3){
    return <h3>this is h3</h3>
  }
}
function App() {
  return (
    <div className="App">
      {getHTag(1)}
      {getHTag(2)}
      {getHTag(3)}
    </div>
  );
}

JSX样式处理

// JSX样式控制
// 1,内敛样式 -- 在元素上绑定一个style属性即可
// 2,类名样式 -- 在元素上绑定一个className属性即可
// 3,动态控制类名
import './app.css';

const h2Style = {
  color:'red',
  fontSize:'30px'
}

const active = false
function App() {
  return (
    <div className="App">
      <span style={
   
   {color:'red',fontSize:'30px'}}>this is span</span>
      <h2 style={h2Style}>this is span</h2>
      <h3 className='active'>this is blue h3</h3>
      <h3 className={active?'active':'default'}>this is blue h3</h3>
    </div>
  );
}

app.css

.active{
    color: blue;
}
.default{
    color: aqua;
}

JSX注意事项

  • JSX必须有一个根节点,如果没有根节点,可以使用一个<></>(幽灵节点)替代

  • 所有标签必须形成闭合,成对闭合或者自闭合

  • JSX中的语法更加贴近JS语法,属性名采用驼峰命名,class->className,for-> htmlFor

  • JSX支持多行(换行),如果需要换行,需要使用()包裹,防止bug出现

如下:没有根节点,会报错

在这里插入图片描述

可以使用幽灵节点

在这里插入图片描述

vscode使用

使用如下的setting,安装插件prettier,error lens

{
  "git.enableSmartCommit": true,
  // 修改注释颜色
  "editor.tokenColorCustomizations": {
    "comments": {
      "fontStyle": "bold",
      "foreground": "#82e0aa"
    }
  },
  // 配置文件类型识别
  "files.associations": {
    "*.js": "javascript",
    "*.json": "jsonc",
    "*.cjson": "jsonc",
    "*.wxss": "css",
    "*.wxs": "javascript"
  },
  "extensions.ignoreRecommendations": false,
  "files.exclude": {
    "**/.DS_Store": true,
    "**/.git": true,
    "**/.hg": true,
    "**/.svn": true,
    "**/CVS": true,
    "**/node_modules": false,
    "**/tmp": true
  },
  // "javascript.implicitProjectConfig.experimentalDecorators": true,
  "explorer.confirmDragAndDrop": false,
  "typescript.updateImportsOnFileMove.enabled": "prompt",
  "git.confirmSync": false,
  "editor.tabSize": 2,
  "editor.fontWeight": "500",
  "[json]": {},
  "editor.tabCompletion": "on",
  "vsicons.projectDetection.autoReload": true,
  "editor.fontFamily": "Monaco, 'Courier New', monospace, Meslo LG M for Powerline",
  "[html]": {
    "editor.defaultFormatter": "vscode.html-language-features"
  },
  "editor.fontSize": 16,
  "debug.console.fontSize": 14,
  "vsicons.dontShowNewVersionMessage": true,
  "editor.minimap.enabled": true,
  "emmet.extensionsPath": [
    ""
  ],
  // vue eslint start 保存时自动格式化代码
  "editor.formatOnSave": true,
  // eslint配置项,保存时自动修复错误
  "editor.codeActionsOnSave": {
    "source.fixAll": true
  },
  "vetur.ignoreProjectWarning": true,
  // 让vetur使用vs自带的js格式化工具
  // uni-app和vue 项目使用
  "vetur.format.defaultFormatter.js": "vscode-typescript",
  "javascript.format.semicolons": "remove",
  // // 指定 *.vue 文件的格式化工具为vetur
  "[vue]": {
    "editor.defaultFormatter": "octref.vetur"
  },
  // // 指定 *.js 文件的格式化工具为vscode自带
  "[javascript]": {
    "editor.defaultFormatter": "vscode.typescript-language-features"
  },
  // // 默认使用prettier格式化支持的文件
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "prettier.jsxBracketSameLine": true,
  // 函数前面加个空格
  "javascript.format.insertSpaceBeforeFunctionParenthesis": true,
  "prettier.singleQuote": true,
  "prettier.semi": false,
  // eslint end
  // react
  // 当按tab键的时候,会自动提示
  "emmet.triggerExpansionOnTab": true,
  "emmet.showAbbreviationSuggestions": true,
  "emmet.includeLanguages": {
    // jsx的提示
    "javascript": "javascriptreact",
    "vue-html": "html",
    "vue": "html",
    "wxml": "html"
  },
  // end
  "[jsonc]": {
    "editor.defaultFormatter": "vscode.json-language-features"
  },
  // @路径提示
  "path-intellisense.mappings": {
    "@": "${workspaceRoot}/src"
  },
  "security.workspace.trust.untrustedFiles": "open",
  "git.ignoreMissingGitWarning": true,
  "window.zoomLevel": 1
}

猜你喜欢

转载自blog.csdn.net/qq_39225271/article/details/127142776