对jsx自己的理解

92 阅读1分钟
function Comp() {
  return <button>btn</button>
}

<Comp className='demo' attr='12'>
inder
<p id='p'>p</p>
<span id='span'></span>
</Comp>

转化为

function Comp() {
  return React.createElement("button", null, "btn");
}

React.createElement(Comp, {
  className: "demo",
  attr: "12"
}, "inder",React.createElement("p", {
  id: "p"
}, "p"), React.createElement("span", {
  id: "span"
}));

使用 JSX 编写的代码将会被转换成使用 React.createElement() 的形式。如果使用了 JSX 方式,那么一般来说就不需要直接调用 React.createElement(),在大多数情况下我们都是直接下这种语法糖。

对React.createElement()的各参数理解:

React.createElement(
  type,
  [props],
  [...children],标签或者是组件中的内容
)

1.type,类型参数可以为标签,或者是react组件,又或者是reactFragment联合组件类型,根据规定如果是标签,第一个字母就是小写,组件第一个字符就是大写。

2.[props],属性参数

3.[...children],标签或者是组件中的内容,通过this.props.children数组拿到组件或者标签中的内容,本质上属性和内容都会通过props传进去

注意:jsx只能有一个根结点,用{}来应用js表达式,和动态数据值,null和undefined代表空元素,在括号中不能直接使用对象,函数,正则。但是可用数组。但是给jsx元素设置样式,用style时,style={{color:'red'}} 不能是字符串,必须是对象