美文网首页
React基础入门

React基础入门

作者: kevin5979 | 来源:发表于2020-09-20 18:09 被阅读0次

React 介绍

百度百科

  • React 起源于 Facebook 的内部项目,因为该公司对市场上所有 JavaScript MVC 框架,都不满意,就决定自己写一套,用来架设Instagram 的网站。做出来以后,发现这套东西很好用,就在2013年5月开源了。

  • React主要用于构建UI。你可以在React里传递多种类型的参数,如声明代码,帮助你渲染出UI、也可以是静态的HTML DOM元素、也可以传递动态变量、甚至是可交互的应用组件。
    特点:
    1.声明式设计:React采用声明范式,可以轻松描述应用。
    2.高效:React通过对DOM的模拟,最大限度地减少与DOM的交互。
    3.灵活:React可以与已知的库或框架很好地配合。

使用react

在使用react 之前,需要先引入三个依赖
react:包含react所必须的核心代码
react-dom:react渲染在不同平台所需要的核心代码
babel:将jsx转换成React代码的工具

  • 通过CDN引入
// crossorigin属性: 拿到跨域脚本的错误信息
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
  • 下载后,添加本地依赖
  • 通过npm管理(后续脚手架再使用)

书写Hello World

<div id="app"></div>

  <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

  <script type="text/babel">
    // 添加 type="text/babel" 来告诉浏览器,使用babel解析
    // 通过ReactDom对象来渲染内容
    ReactDOM.render(<h2>Hello World</h2>, document.getElementById("app"));
  </script>

代码体验

  • 案例: 实现点击按钮改变文本内容
// 定义一个es6的类 App
  class App extends React.Component {
    // 继承父类的实例属性
    constructor(props) {
      super(props);
      // 定义类的属性集合
      this.state = {
        message: "Hello World"
      }
    }

    // 改变文本
    chang() {
      this.setState({
        message: "Hello React"
      })
    }
    // 渲染函数
    render() {
      return (
        <div>
          {/*绑定文本*/}
          <h2>{this.state.message}</h2>
          {/*绑定函数*/}
          <button onClick={this.chang.bind(this)}>点击改变文本</button>
        </div>
      )
    }
  }
// 将App类中render的返回值写入到div#app中
ReactDOM.render(<App/>, document.getElementById("app"))
Hello World

条件判断渲染

  • 案例:判断用户是否登录,已登录显示用户名,未登录显示请登录字样
  class App extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        isLogin: false,
        userName: "kevin"
      }
    }

    render() {
      const {isLogin, userName} = this.state
      const isDisplay = isLogin ? "block" : "none"
      return (
        // 这里为jsx语法
        // 返回值中只能有一个根标签
        <div>

          {
            // 条件判断
            this.state.isLogin ? <h2>欢迎回来~</h2> : <h2>请先登录~</h2>
          }
          // 书写style 用 {{}} 包裹
          <h2 style={{display: isDisplay}}>{userName}</h2>
          <button onClick={this.loginBtn.bind(this)}>{this.state.isLogin ? "退出" : "登录"}</button>
        </div>
      )
    }
    // 点击事件
    loginBtn() {
      this.setState({
        isLogin: !this.state.isLogin
      })
    }
image.png

循环渲染

  • 案例:根据数组的值渲染
  class App extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        songs: ["光辉岁月", "你最珍贵", "有多少爱可以重来", "宝贝对不起", "风往北吹", "白天不懂夜的黑", "明明白白我的心"],
        price: [10, 30, 120, 453, 55, 78, 111, 222]
      }
    }

    render() {
      let songsList = this.state.songs.map((item, index) => <li key={index}>{index} - {item}</li>)
      let priceList = this.state.price.filter(item => item >= 50).slice(0, 3).map(item => <li key={item}>{item}</li>)
      return (
        <div>
          <ul>{songsList}</ul>
          <ul>{priceList}</ul>
        </div>
      )
    }
  }
image.png

属性绑定
// 属性绑定: 属性名 = {}
// 样式绑定: style = {{fontSize : "30px"}}
// 类名绑定: className = {"name1","name2",...}

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

      this.state = {
        title: "React",
        imgUrl: "https://dss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1141259048,554497535&fm=26&gp=0.jpg",
        link: "https://www.baidu.com",
        active: false
      }
    }

    render() {
      return (
        <div>
          <h2 title={this.state.title}>Hello World</h2>
          <img src={this.state.imgUrl} style={{ width:"200px" }} alt=""/>
          <a href={this.state.link} target="_blank">百度一下</a>
          <div className={"message " + (this.state.active ? "active": "")}>abc</div>
          <div className={["message",(this.state.active ? "active" : "")].join(" ")}>abc</div>
          <div style={{fontSize: "30px", color: "red", backgroundColor: "blue"}}>我是文本</div>
        </div>
      )
    }
  }

事件绑定

  class App extends React.Component {
    render() {
      return (
        <div>
          <button onClick={this.btnClick}>点我一下</button>
        </div>
      )
    }

    btnClick() {
      console.log(this)
    }
  }
image.png
  • this指向不正确 原因是btnClick函数并不是我们主动调用的,而且当button发生改变时,React内部调用了btnClick函数;
    而它内部调用时,并不知道要如何绑定正确的this;

  • 解决this问题

  1. bind绑定
<button onClick={this.btnClick.bind(this)}>点我一下</button>
class App extends React.Component {
    constructor(props) {
      super(props);
      this.btnClick = this.btnClick.bind(this);
    }
}
  1. 使用es6箭头函数
<button onClick={this.btnClick}>点我一下</button>

btnClick = () => {
      console.log(this);
 }
  1. 事件监听时传入箭头函数(推荐)
<button onClick={() => this.btnClick()}>点我一下</button>

btnClick() {
      console.log(this);
}
image.png

函数参数传递

  • 传递事件对象
  • 案例:阻止a标签的默认跳转
  class App extends React.Component {
    constructor(props) {
      super(props)
      this.state = {}
    }

    render() {
      return (
        <div>
          <a href="http://www.baidu.com" onClick={this.btnClick}>点我一下</a>
        </div>
      )
    }

    // 默认传递事件对象 e
    btnClick(e) {
      console.log(e);
      e.preventDefault();
    }
  }
image.png
  • 获取更多参数
class App extends React.Component {
    constructor(props) {
      super(props);

      this.state = {
        names: ["衣服", "鞋子", "裤子"]
      }
    }

    render() {
      return (
        <div>
          {
            this.state.names.map((item, index) => {
              return (
                <a href="#" key={index} onClick={e => this.aClick(e, item, index)}>{item}</a>
              )
            })
          }
        </div>
      )
    }

    aClick(e, item, index) {
      console.log(item, index);
      console.log(e);
      e.preventDefault();
    }
  }
image.png

相关文章

网友评论

      本文标题:React基础入门

      本文链接:https://www.haomeiwen.com/subject/xdzrhktx.html