React基本认识与环境搭建&JSX&相关语法知识点

# 资料速览

React 官网:https://reactjs.bootcss.com/docs/hello-world.html

Create React App 中文文档

快速入门帮助 GitHub

TypeScript 中文手册:[这篇快速上手指南会教你如何将 TypeScript 与 React 结合起来使用](https://typescript.bootcss.com/tutorials/react.html)

React Router 和 @ reach /router 的未来:文档https://reactrouter.com/web/api/NavLink/activeclassname-string

# react 开发环境的搭建

  1. react.js // react 核心文件
  2. react-dom.js // 渲染页面中的 DOM,必须依赖 react 核心文件
  3. babel.js // ES6 => ES5

下载

  • react 核心包 : npm i react --save

  • React-dom : npm i react-dom --save

  • Babel: npm install --save @babel/standalone : 多用于开发环境测试简单 demo:详细介绍 ;如果您在生产中使用 Babel,通常不应使用 @ babel /standalone。相反,您应该使用在 Node.js 上运行的构建系统(例如 Webpack,Rollup 或 Parcel)来提前转换 JS。 提前转换 js 的用法

但是,@ babel /standalone 有一些有效的用例:

  • 它提供了使用 Babel 进行原型制作的简便方法。使用 @ babel /standalone,您可以在 HTML 中仅使用一个简单的脚本标签就开始使用 Babel。
  • 实时编译用户提供的 JavaScript 的站点,例如 JSFiddleJS BinBabel 站点上的 REPLJSitor 等。
  • 直接嵌入 JavaScript 引擎(例如 V8)并希望使用 Babel 进行编译的应用
  • 想要使用 JavaScript 作为脚本语言来扩展应用程序本身的应用程序,包括 ES2015 提供的所有功能。
  • 其他非 Node.js 环境(ReactJS.NETruby-babel-transpilerphp-babel-transpiler 等)。

基本结构:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="node_modules/react/umd/react.development.js"></script>
    <script src="node_modules/react-dom/umd/react-dom.development.js"></script>
    <script src="node_modules/@babel/standalone/babel.min.js"></script>
</head>

<body>
    <!--  创建dom根结点 -->
    <div id="app"></div>

    <script type="text/babel">
        ReactDOM.render(<h1>hello React</h1>,document.getElementById('app'))
    </script>
</body>

</html>

NpCnFx

# jsx 注释

let word = <h1>
           {/* 这是注释 */} 
            hello world
            </h1>
        ReactDOM.render(word,document.getElementById('app'))

# JSX 多行标签需要一个父元素包裹

let word = <div>
            <h1>12313</h1> 
            <h2>123132</h2>
        </div>

# JSX 变量

<script type="text/babel">
        let first = 'hello'
        let last = 'world'
        let obj = {
            name:'zc',
            age: 18
        }
        function getName(obj){
            return `你的名字是 ${obj.name},年龄是 ${obj.age}`
        }
        let word =(
            <div>
                <h3>{first}</h3>
                <h3>{last}</h3>
                <h1>{getName(obj)}</h1>
           </div>
        )
        ReactDOM.render(word,document.getElementById('app'))
    </script>

q28oVY

# 渲染数组

let arr = [
  '哈哈哈哈哈1',
  '哈哈哈哈哈2',
  '哈哈哈哈哈3',
  '哈哈哈哈哈4',
  '哈哈哈哈哈5',
  '哈哈哈哈哈6',
  '哈哈哈哈哈7']
let word = (
  <div>
  {arr.map(item =>{
   return <p>{item}</p> 
  })}   
  </div>
)   
ReactDOM.render(word,document.getElementById('app'))

# 属性设置

let text = '点我去百度'
let linkUrl = 'https://baidu.com'
let myDom = <a className='demo' href={linkUrl}>点我</a>

注意: 在 JSX 中 不能使用 class,这个属性,因为 class 是 js 的关键字。 – 代替使用 className

# 无状态组件 (函数组件)

<body>
    <!--  创建dom根结点 -->
    <div id="app"></div>
    <script type="text/babel">
        function Com(){
            return (
                <div>
                    <div>hello world</div>
                    <div>zhou chen</div>
                </div>
                
            )
        }
        ReactDOM.render(<Com/>,document.getElementById('app'))
    </script>
</body>

# 无状态组件传递参数

Props

function Father(props){
           return(
               <div>
                   <p>我是一个无状态函数组件 -- 父亲</p>
                   <h3>{props.name}</h3>   
                   <h3>{props.age}</h3>   
                   <h3>{props.sex}</h3>   
               </div>
           )
       }

       let msg = '我是一个变量'
       let obj = {
           name:'zc',
           age: 18,
           sex : 1
       }
       ReactDOM.render(<Father {...obj}/>,document.getElementById('app'))

# 类组件传递参数

this.props.xxx

class MyCom extends React.Component{
  render(){
    return (
      <div>
        <div>hello world</div>
        <MySon/>
        <h1>{this.props.name}</h1>
        <h1>{this.props.age}</h1>
        <h1>{this.props.sex}</h1>
			</div>
)
}   
}
let msg = '我是一个变量'
let obj = {
  name:'zc',
  age: 18,
  sex : 1
}
ReactDOM.render(<MyCom {...obj}/>,document.getElementById('app'))

hThktC

# 无状态组件的 props 验证 和默认值

随着你的应用程序不断增长,你可以通过类型检查捕获大量错误。对于某些应用程序来说,你可以使用 FlowTypeScript 等 JavaScript 扩展来对整个应用程序做类型检查。但即使你不使用这些扩展,React 也内置了一些类型检查的功能。要在组件的 props 上进行类型检查,你只需配置特定的 propTypes 属性:

默认值:您可以通过配置特定的 defaultProps 属性来定义 props 的默认值: :react 版本要求 16 以后;

props 验证: propTypes 验证类型

官网用法:官网

默认值:

function Com(props){
  return (
    <div>
    <p>{props.msg}</p>
    </div>

  )
}
Com.defaultProps = {
  msg :'默认值'
}

ReactDOM.render(<Com />,document.getElementById('app'))

props 类型验证

  • 引用 prop-types 库。 — npm i prop-types --save
<script type="text/babel">
  function Com(props){
  return (
    <div>
    <p>{props.msg}</p>
    <p>{props.age}</p>
    </div>

  )
}

// 默认值
Com.defaultProps = {
  msg :'默认值'
}

// props 类型验证
Com.propTypes = {
  msg : PropTypes.number,
  age:PropTypes.number.isRequired
}

ReactDOM.render(<Com msg = {'1111'} age = {18}/>,document.getElementById('app'))
  </script>

VJA0vp

import PropTypes from 'prop-types';

class Greeting extends React.Component {
  render() {
    return (
      <h1>Hello, {this.props.name}</h1>
    );
  }
}

Greeting.propTypes = {
  name: PropTypes.string
};

# 类组件的 props 验证 和默认值

默认值:您可以通过配置特定的 defaultProps 属性来定义 props 的默认值: :react 版本要求 16 以后;

props 验证: propTypes 验证类型

默认值 :( 传统写法 )

class MyCom extends React.Component{
  render(){
    return (
      <div>
        <div>hello world</div>
        <p>{this.props.name}</p>
			</div>
		)
	}   
}

// 传统写法 -- 默认值
MyCom.defaultProps = {
  name:'zc'
}
let msg = '我是一个变量'

ReactDOM.render(<MyCom />,document.getElementById('app'))

类型验证:(传统写法)

class MyCom extends React.Component{
  render(){
    return (
      <div>
        <div>hello world</div>
        <p>{this.props.name}</p>
		</div>
		)
	}   
}

MyCom.defaultProps = {
  name:'zc'
}  

MyCom.propTypes = {
  name: PropTypes.string.isRequired
}

ReactDOM.render(<MyCom name={1}/>,document.getElementById('app'))

利用 static

class MyCom extends React.Component{
          static defaultProps = {
              name:'zc'
          }

          static propTypes = {
              name: PropTypes.string.isRequired
          }

          render(){
              return (
                  <div>
                      <div>hello world</div>
                      <p>{this.props.name}</p>
                  </div>
            )
          }   
      }

# 类组件 state 状态

class Father extends React.Component{
        constructor(props){
            super(props)
            // state状态
            this.state = {
                msg : 'hello world'
            }
        }
        render(){
            return(
                <div>
                    <p>{this.state.msg}</p>    
                </div>
            )
        }

  }

   ReactDOM.render(<Father/>,document.getElementById('app'))

# setState 是异步的

class Father extends React.Component{
           constructor(props){
               super(props)
               this.state = {
                   msg : 'hello world'
               }
           }

           handle = (data)=>{
               this.setState({
                   msg:'zczczczc'
               },()=>{
                   console.log(this.state.msg);
               })    

           }
           render(){
               return(
                   <div>
                       <p>{this.state.msg}</p>    
                       <button onClick = {this.handle}>点我</button>
                   </div>
               )
           }

     }

# 字符串标签插入(字符串 => HTML)

官网说明:https://reactjs.org/docs/dom-elements.html

<div dangerouslySetInnerHTML={{__html:this.state.newHtml}}></div>

# 事件绑定 和 this

React 元素的事件处理和 DOM 元素的很相似,但是有一点语法上的不同:

  • React 事件的命名采用小驼峰式(camelCase),而不是纯小写。
  • 使用 JSX 语法时你需要传入一个函数作为事件处理函数,而不是一个字符串。

# 修改 this 指向

  1. bind 方式显示绑定
  2. 函数通过箭头函数进行创建
  3. constructor 中提前进行绑定
  4. 把事件的调用写成箭头函数的调用方式

# bind 方式显示绑定

class Com extends React.Component{
           constructor(props){
                super(props)

           }

           handle(){
               console.log(this);
           }

           render(){
               return(
                   <div>
                        <h1>121131</h1>
                        <button onClick={this.handle.bind(this)}>点击</button>
                    </div>
               )
           }
       }

# 函数通过箭头函数进行创建

class Com extends React.Component{
          constructor(props){
               super(props)

          }

          handle= ()=>{
              console.log(this);
          }

          render(){
              return(
                  <div>
                       <h1>121131</h1>
                       <button onClick={this.handle}>点击</button>
                   </div>
              )
          }
      }

# constructor 中提前进行绑定

class Com extends React.Component{
          constructor(props){
               super(props)
               this.handle = this.handle.bind(this)
          }

          handle(){
              console.log(this);
          }

          render(){
              return(
                  <div>
                       <h1>121131</h1>
                       <button onClick={this.handle}>点击</button>
                   </div>
              )
          }
      }

# 把事件的调用写成箭头函数的调用方式

class Com extends React.Component{
          constructor(props){
               super(props)
          }

          handle(){
              console.log(this);
          }

          render(){
              return(
                  <div>
                       <h1>121131</h1>
                       <button onClick={()=>this.handle()}>点击</button>
                   </div>
              )
          }
      }

# 传递参数

<button onClick={this.handle.bind(this,'xxxx')}>点击</button>

<button onClick={()=>this.handle('xxxx')}>点击</button>

# Event 事件对象

class Com extends React.Component{
           constructor(props){
                super(props)
           }

           handle(p){
               console.log(p);
               console.log(this);
           }

           render(){
               return(
                   <div>
                        <h1>121131</h1>
                        <button onClick={(e)=>this.handle(e)}>点击</button>
                    </div>
               )
           }
       }

# 条件渲染

在 React 中,你可以创建不同的组件来封装各种你需要的行为。然后,依据应用的不同状态,你可以只渲染对应状态下的部分内容。

React 中的条件渲染和 JavaScript 中的一样,使用 JavaScript 运算符 if 或者条件运算符去创建元素来表现当前的状态,然后让 React 根据它们来更新 UI。

# 状态提升

通常,多个组件需要反映相同的变化数据,这时我们建议将共享状态提升到最近的共同父组件中去。

class Demoa extends React.Component {
   constructor(props) {
     super(props);
   }

   render() {
     return (
       <div>
         <h1>我的demoa ---- {this.props.msg}</h1>
       </div>
     );
   }
 }
 class Demob extends React.Component {
   constructor(props) {
     super(props);
   }

   render() {
     return (
       <div>
         <h1>我的demob  ---- {this.props.msg}</h1>
       </div>
     );
   }
 }

 class Com1 extends React.Component {
   constructor(props) {
     super(props);
     this.state = {
         msg: '我是2个组件都用的数据'
     }
   }


   handle(){
       this.setState({
           msg:'我被修改了'
       })
   }
   render() {
     return (
       <div>
         <h1>我是组件</h1>
         <Demoa msg = {this.state.msg}/>
         <Demob msg = {this.state.msg}/>
         <button onClick = {()=>this.handle()}>修改</button>
       </div>
     );
   }
 }
 ReactDOM.render(<Com1 />, document.getElementById("app"));

AiYlXZ

# 相关 Error

jDVqvD

错误原因:组件名字首写字母要大写字母。

6dGfpO

错误原因:React.component => **React.Component. 拼写错误。

20ng4N

错误原因:class 类组件、super () 没有被调用。

Tb902w

错误原因:父组件传递过来的参数 为调用某一项~

Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2015-2021 zhou chen
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信