用 JSX 简化代码

  • babel-loader,webpack 已内置
  • JSX 能将标签转换成 react 语法:babel online
  • class 必须写成 className
  • 插入变量: 在 {} 中写 JS 代码
  • 插入对象:用 {} 把对象包起来,如 {{age:18}}
  • 习惯在 return 后面加 ()

以下方法一般不用:

  1. <script type-'text/babel'>
  2. let n = 1;
  3. // 相当于 React.createElement()
  4. const App = () => (
  5. <div>
  6. {n} // 1
  7. <button onClick={() => {
  8. n += 1;
  9. render();
  10. }}>+1</button>
  11. </div>
  12. );
  13. const render = () => ReactDOM.render(<App />, document.querySelector('#root'));
  14. render();
  15. </script>

一般使用 export 和 import:

  1. // App.js
  2. import React from 'react';
  3. import ReactDOM from 'react-dom';
  4. let n = 1;
  5. // 相当于 React.createElement()
  6. const App = () => (
  7. <div>
  8. {n} // 1
  9. </div>
  10. );
  11. export default App
  1. // index.js
  2. import React from 'react';
  3. import ReactDOM from 'react-dom';
  4. import App from './App.js';
  5. const root = document.querySelector('#root');
  6. ReactDOM.render(<App />, root);

JSX 条件判断

  1. const Component1 = () => {
  2. return (
  3. <div>
  4. { n % 2 === 0 ? <div> even </div> : <div> odd </div>}
  5. </div>
  6. )
  7. }
  8. const Component2 = () => {
  9. const content = (
  10. <div>
  11. { n % 2 === 0 ? <div> even </div> : <div> odd </div> }
  12. </div>
  13. )
  14. return content
  15. }
  16. const Component3 = () => {
  17. let inner;
  18. if (n % 2 == 0) {
  19. inner = <div>even</div>
  20. } else {
  21. inner = <div>odd</div>
  22. }
  23. const content = (
  24. <div> {inner} </div>
  25. )
  26. return content
  27. }

JSX 循环语句

  1. const Component1 = (props) => {
  2. return (
  3. <div>
  4. {
  5. props.numbers.map((n, index) => {
  6. return <div>{ index } - { n }</div>
  7. })
  8. }
  9. </div>
  10. )
  11. }
  12. const Component2 = (props) => {
  13. const array = []
  14. for (let i=0; i<props.numbers.length; i++) {
  15. array.push(<div>{i} - { props.numbers[i] }</div>)
  16. }
  17. return <div>{ array }</div>
  18. }