这是官网上的一个简单的例子
const name = 'Josh Perez'; const element = <h1>Hello, {name}</h1>; ReactDOM.render( element, document.getElementById('root') );
从中可以看到:
React.createElement()
调用。<ul title='aa'> <li>hello</li> </ul>
这段代码在react里,因为我们使用react的时候都会引入react,因此react会自动解析成
React.createElement('ul',{ title:'aa' },React.createElement('li',{},'hello'))
这两段代码所表示出来的结果是一样的
由此可以看出,react会将jsx花括号中的内容转化成js代码
这样,
从本质上讲,JSX 只是为 React.createElement(component, props, ...children)
函数提供的语法糖。
因为 JSX 被编译为 React.createElement
的调用,所以 React
库必须在你 JSX 代码的作用域中。
官网建议给组件以大写字母开头的方式命名。如果你已经有以小写字母开头的组件,需要在 JSX 中使用前,将其赋值给以大写字母开头的变量。
因为在react中,组件的引用必须是首字母大写,否则无法达到想要的结果
JSX 中的 props(属性)
属性有以下几种形式
1、你可以传递任何一个用 {}
包裹的 JavaScript 表达式作为 props(属性)
//JavaScript 表达式作为 props(属性) <MyComponent foo={1 + 2 + 3 + 4} />
2、你可以传入一个字符串字面量作为一个 props(属性)
<MyComponent message="hello world" /> <MyComponent message={'hello world'} />
3、如果你没给 prop(属性) 传值,那么他默认为 true
<MyTextBox autocomplete />
<MyTextBox autocomplete={true} />
4、如果你已经有一个 object 类型的 props
,并且希望在 JSX 中传入,你可以使用扩展操作符 ...
传入整个 props 对象。
function App1() { return <Greeting firstName="Ben" lastName="Hector" />; } function App2() { const props = {firstName: 'Ben', lastName: 'Hector'}; return <Greeting {...props} />; }
JSX 中的 Children(子元素)
1、您可以在开放标签和闭合标签中放入一个字符串,那么 props.children
就是那个字符串。这对于内置很多 HTML 元素时非常有用
<MyComponent>Hello world!</MyComponent>
2、通过使用 {}
包裹,你可以将任何的 JavaScript 元素而作为 children(子元素) 传递
<MyComponent>foo</MyComponent> <MyComponent>{'foo'}</MyComponent>
3、props.children
的值可以是回调函数
// Calls the children callback numTimes to produce a repeated component function Repeat(props) { let items = []; for (let i = 0; i < props.numTimes; i++) { items.push(props.children(i)); } return <div>{items}</div>; } function ListOfTenThings() { return ( <Repeat numTimes={10}> {(index) => <div key={index}>This is item {index} in the list</div>} </Repeat> ); }
4、false
,null
,undefined
,和 true
都是有效的的 children(子元素) 。但是并不会被渲染,下面的JSX表达式渲染效果是相同的,都是空
<div /> <div></div> <div>{false}</div> <div>{null}</div> <div>{undefined}</div> <div>{true}</div>
在有条件性渲染 React 元素时非常有用。如果 showHeader
为 true
时,<Header />
会被渲染
<div> {showHeader && <Header />} <Content /> </div>
如果本文对您有帮助,请抬抬您的小手,点下右下角的推荐, ^-^,当然如果看了这篇博客对您有帮助是我最开心的事,毕竟赠人玫瑰,手有余香, ^-^,如果这篇博客没有帮助到您,那就只能说一声抱歉啦