0


react 第一个项目

sudo npx create-react-app reactdemo01

npx node.js工具

create-react-app 核心包(固定写法)用于创建react项目

后跟项目名层

启动一个新的 React 项目 – React 中文文档

//项目的根组件
//App -> index.js ->/Users/king/Documents/reactapp/reactdemo01/public/index.html 的root
function App() {
  return (
    <div className="App">
      this is app 
    </div>
  );
}

export default App;
// 核心包
import React from 'react';
import ReactDOM from 'react-dom/client';
//根组件
import App from './App';
// 把App组件渲染到id为root的dom节点上
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <App />
);

遇到的问题

保存 "App.js"失败: 权限不足。选择 "以超级用户身份重试" 以超级用户身份重试。

sudo chown -Rv 用户名 项目路径

JSX

JSX 是javascript 和xml (html)的缩写,表示在js代码中编写html模版结构 它是react中编写UI模版的方式

优势

1.html 声明式模版写法

2.js的可编程能力

jsx的本质

jsx本质不是标准的js语法 它是js的语法扩展 浏览器本身并不能识别 需要通过解析工具做解析之后才能在浏览器中运行

Babel · Babel

jsx中使用js表达式

//项目的根组件
//App -> index.js ->/Users/king/Documents/reactapp/reactdemo01/public/index.html 的root
function getName() {
  return "return name"
}
const count = 100
function App() {
  return (
    <div className="App">
      this is app 
      {/*使用引号传递字符串*/}
      {'this is message'}
      {/*识别js变量 */}
      {count}
      {/*函数调用 */}
      {getName()}
      {/*方法调用 */}
      {new Date().getDate()}
      {/*使用js对象*/}
      <div style={{color: 'red'}}> 20240117 </div>
    </div>
  );
}

export default App;

在jsx中可以通过大括号{}识别javascrip中的表达式 比如常见的变量函数调用 方法调用等

if switch 变量声明等语句 不是表达式不能在{}中

实现渲染

列表

import logo from './logo.svg';
import './App.css';
const list = [
  {id:1001,name:"张三"},
  {id:1002,name:"李四"},
  {id:1003,name:"王二"},
  {id:1004,name:"麻子"}
]
function App() {
  return (
    <div className="App">
      hello world
      {/*列表渲染
        map 遍历哪个结构 return 结构
        注意事项 加上一个独一无二的key 字符串或者numberid 
        key 的作用 react 框架内部使用 提升更新新能
      */}
      <ul>
        {list.map(item =>  <li key={item.id}>  {item.name}</li>)}
      </ul>
    </div>
  );
}

export default App;

条件渲染

const isLogin = false
function App() {
  return (
    <div className="App">
      hello world
      {isLogin && <span> this is App  </span>}
      {isLogin ? <span>lock</span> : <span>xxxxx</span>}
    </div>
  );
}
const info_type = 1
function create_widget() {
  if (info_type == 1) {
    return  <div>两个喜鹊叫喳喳</div>
  } else if (info_type == 2) {
    return  <div>树上的鸟儿成双对</div>
  } else if (info_type == 3) {
    return  <div>河边两个小娃在钓鱼</div>
  } else {
    return  <div>俩娃妈妈拿着刺条去河边</div>
  }

}
function App() {
  return (
    <div className="App">
      {create_widget()}
    </div>
  );
}

export default App;

本文转载自: https://blog.csdn.net/weixin_38432324/article/details/135663314
版权归原作者 weixin_38432324 所有, 如有侵权,请联系我们删除。

“react 第一个项目”的评论:

还没有评论