React学习笔记

REACT笔记2(基础)

2018-07-17  本文已影响0人  XKolento
1.vscode配置 html 标签快捷键

编辑器左下角→设置 复制如下代码片段黏贴进右侧保存
打开 setting.json

{
    "git.ignoreMissingGitWarning": true,
    "editor.quickSuggestions": {
        "strings": true
    },
    "workbench.colorTheme": "Monokai",
    "window.zoomLevel": 0,
    "emmet.triggerExpansionOnTab": true,
    "emmet.includeLanguages": {
        "javascript": "javascriptreact"
    }
}
2.registerServiceWorker();

新搭建好的react脚手架中会自动存在一个这样的方法,主要是用于在生产环境用,为用户本地创建一个service worker来缓存资源到本地,提升访问的性能。

// In production, we register a service worker to serve assets from local cache.

// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on the "N+1" visit to a page, since previously
// cached resources are updated in the background.

// To learn more about the benefits of this model, read https://goo.gl/KwvDNy.
// This link also includes instructions on opting out of this behavior.
3.了解jsx
const kolento = <p className="hello">Hello World</p>

jsx是一种js语法的扩展,专门用于react框架中,在React中推荐使用jsx来描述用户界面,它是由javascript中实现的。
目前不需要创建后缀为jsx的文件,js后缀文件也自动识别jsx。

在jsx中可以任意的使用js表达式,只要把表达式包含在大括弧里面即可。

function name(user){
    return user.firstname+''+user.lastname
}
const user = {
    firstname:'hello',
    lastname:'world'
}
const element = (
  <p>{name(user)}</p>
)//此处添加括弧是为了,防止分号自动插入导致bug
React.render(
    element,document.getElementById('root')
)

在jsx编译之后,会转化为普通的javascript对象

可以在jsx中使用if或者for语句等

function getGreeting(user) {
  if (user) {
    return <h1>Hello, {formatName(user)}!</h1>;
  }
  return <h1>Hello, Stranger.</h1>;
}
4.jsx的属性与值

①可以使用引号来定义以字符串为值的属性

const test = <h1 tabIndex="0"></h1>

②可以使用大括弧来定义以js表达式为值的属性

const img = <img src={user.image} />
5.jsx的嵌套

①如果jsx是闭合的标签,则需要的标签结尾处写/>,有点类似于html,xml
②jsx标签可以进行互相嵌套,前提是最外层只能有一个根节点,就是必须要有一个div包裹,类似vue

const element = (
    <div>
        <p>hello</p>
        <p>react</p>
    </div>
);

注意:jsx的命名都需要按照驼峰的方式
因为他的特性更接近js,而不是HTML
class应该写成className
tabindex应该写成tabIndex

6.jsx防注入攻击

reactDOM在渲染之前会过滤所有传入的值,
它可以确保你的应用不会被注入攻击,所有的内容在渲染之前都会被替换成字符串,这样可以有效的防止XSS(跨站脚本攻击)

7.jsx代表Objects

babel编译器会把jsx转化为一个名为 React.createElement()的方法调用

const element = (<h1 className="title">hello world</h1>);
const element2 = React,createElement(
    'h1',
    {className:'title'},
    'hello world'
)

以上的例子为完全一样的效果

上一篇 下一篇

猜你喜欢

热点阅读