這是官網上的一個簡單的例子
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>
如果本文對您有幫助,請抬抬您的小手,點下右下角的推薦, ^-^,當然如果看了這篇博客對您有幫助是我最開心的事,畢竟贈人玫瑰,手有余香, ^-^,如果這篇博客沒有幫助到您,那就只能說一聲抱歉啦