react学习笔记_01-jsx

2022-10-17,,,

const element = <h1>hello, world!</h1>;

首先我们看到声明了一个element元素,而他的内容并非字符串或者html。

它被称为 jsx,是一个 javascript 的语法扩展我们建议在 react 中配合使用 jsx,jsx 可以很好地描述 ui 应该呈现出它应有交互的本质形式。jsx 可能会使人联想到模版语言,但它具有 javascript 的全部功能。

在 jsx 中嵌入表达式

  下面案例中的{name}则为被嵌入到jsx中的表达式

const name = 'josh perez';
const element = <h1>hello, {name}</h1>;

reactdom.render(
  element,
  document.getelementbyid('root')
);

在 jsx 语法中,你可以在大括号内放置任何有效的 javascript 表达式。例如,2 + 2user.firstnameformatname(user) 都是有效的 javascript 表达式。

function format(user){
    return user.name+'' "+user.gender;
}

const user={
    name:"zhangsan",
    gender:"男"
}

const element=(
  <h1>hello,{format(user)}</h1> ) reactdom.render( element, document.getbyelementid("id") )

jsx 也是一个表达式

在编译之后,jsx 表达式会被转为普通 javascript 函数调用,并且对其取值后得到 javascript 对象。

也就是说,你可以在 if 语句和 for 循环的代码块中使用 jsx,将 jsx 赋值给变量,把 jsx 当作参数传入,以及从函数中返回 jsx

function getgreeting(user) {
  if (user) {
    return <h1>hello, {formatname(user)}!</h1>;
  }
  return <h1>hello, stranger.</h1>;
}

jsx 特定属性:可以在jsx中为html标签元素指定属性,直接赋值方式和使用表达式方式

const element = <div tabindex="0"></div>;
const element = <img src={user.avatarurl}></img>;

jsx 标签里能够包含很多子元素:

const element = (
  <div>
    <h1>hello!</h1>
    <h2>good to see you here.</h2>
  </div>
);

jsx 防止注入攻击:

你可以安全地在 jsx 当中插入用户输入内容:

const title = response.potentiallymaliciousinput;
// 直接使用是安全的:
const element = <h1>{title}</h1>;

react dom 在渲染所有输入内容之前,默认会进行。它可以确保在你的应用中,永远不会注入那些并非自己明确编写的内容。所有的内容在渲染之前都被转换成了字符串。这样可以有效地防止 xss(cross-site-scripting, 跨站脚本)攻击。

 

jsx 表示对象:

  babel 会把 jsx 转译成一个名为 react.createelement() 函数调用。

  以下两种示例代码完全等效:

const element = (
  <h1 classname="greeting">
    hello, world!
  </h1>
);
const element = react.createelement(
  'h1',
  {classname: 'greeting'},
  'hello, world!'
);

react.createelement() 会预先执行一些检查,以帮助你编写无错代码,但实际上它创建了一个这样的对象:

// 注意:这是简化过的结构
const element = {
  type: 'h1',
  props: {
    classname: 'greeting',
    children: 'hello, world!'
  }
};

这些对象被称为 “react 元素”,它们描述了你希望在屏幕上看到的内容。react 通过读取这些对象,然后使用它们来构建 dom 以及保持随时更新。

 

《react学习笔记_01-jsx.doc》

下载本文的Word格式文档,以方便收藏与打印。