用 JSX 简化代码
- babel-loader,webpack 已内置
- JSX 能将标签转换成 react 语法:babel online
- class 必须写成 className
- 插入变量: 在 {} 中写 JS 代码
- 插入对象:用 {} 把对象包起来,如 {{age:18}}
- 习惯在 return 后面加 ()
以下方法一般不用:
<script type-'text/babel'>
let n = 1;
// 相当于 React.createElement()
const App = () => (
<div>
{n} // 1
<button onClick={() => {
n += 1;
render();
}}>+1</button>
</div>
);
const render = () => ReactDOM.render(<App />, document.querySelector('#root'));
render();
</script>
一般使用 export 和 import:
// App.js
import React from 'react';
import ReactDOM from 'react-dom';
let n = 1;
// 相当于 React.createElement()
const App = () => (
<div>
{n} // 1
</div>
);
export default App
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.js';
const root = document.querySelector('#root');
ReactDOM.render(<App />, root);
JSX 条件判断
const Component1 = () => {
return (
<div>
{ n % 2 === 0 ? <div> even </div> : <div> odd </div>}
</div>
)
}
const Component2 = () => {
const content = (
<div>
{ n % 2 === 0 ? <div> even </div> : <div> odd </div> }
</div>
)
return content
}
const Component3 = () => {
let inner;
if (n % 2 == 0) {
inner = <div>even</div>
} else {
inner = <div>odd</div>
}
const content = (
<div> {inner} </div>
)
return content
}
JSX 循环语句
const Component1 = (props) => {
return (
<div>
{
props.numbers.map((n, index) => {
return <div>{ index } - { n }</div>
})
}
</div>
)
}
const Component2 = (props) => {
const array = []
for (let i=0; i<props.numbers.length; i++) {
array.push(<div>{i} - { props.numbers[i] }</div>)
}
return <div>{ array }</div>
}