React 基础

一、JSX 嵌入变量

  • 情况一:当变量是 NumberStringArray 类型时,可以直接显示。
  • 情况二:当变量是 NullundefinedBoolean 类型时,内容为空。
    如果希望显示 NullundefinedBoolean,那么需要转成字符串;
    转换方式有:toString 方法、空字符串拼接、String(变量) 等方式;
  • 情况三:对象类型不能作为子元素。

二、JSX 中绑定 class & style

class:

render() {
  const { active } = this.state;
  return (
    <div>
      {/* 添加 class 属性 */}
      <div className={'a b ' + (active ? 'active' : '')}>box1</div>
      <div className={'a b ' + (active ? '' : 'active')}>box2</div>
    </div >
  )
}

style:

<div style={{ color: 'red', fontSize: '20px', backgroundColor: 'pink' }}>绑定 style 样式</div>

三、JSX 中绑定事件(解决 this 为 undefined)

方案一:通过 bind 绑定 this(显示绑定)

class Demo extends React.Component {
  constructor() {
    super();
    this.state = {
      num: 0
    }
    // 多次调用使用
    this.add = this.add.bind(this);
  }
  render() {
    const { num } = this.state;
    return (
      <div>
        <div>{num}</div>
        {/* 一次调用 */}
        <button onClick={this.add.bind(this)}>加1</button>
        {/* 多次调用 */}
        <button onClick={this.add}>加1</button>
      </div >
    )
  }
  add() {
    this.setState({
      num: this.state.num + 1
    })
  }
}

方案二:定义函数时,使用箭头函数

class Demo extends React.Component {
  constructor() {
    super();
    this.state = {
      num: 0
    }
  }
  render() {
    const { num } = this.state;
    return (
      <div>
        <div>{this.state.num}</div>
        <button onClick={this.add}>加1</button>
      </div >
    )
  }
  // 使用箭头函数
  add = () => {
    this.setState({
      num: this.state.num + 1
    })
  }
}

方案三(推荐):直接传入一个箭头函数,在箭头函数中调用需要执行的方法

class Demo extends React.Component {
  constructor() {
    super();
    this.state = {
      num: 0
    }
  }
  render() {
    const { num } = this.state;
    return (
      <div>
        <div>{this.state.num}</div>
        <button onClick={() => { this.add() }}>加1</button>
      </div >
    )
  }
  // 使用箭头函数
  add() {
    this.setState({
      num: this.state.num + 1
    })
  }
}

四、条件渲染

class Demo extends React.Component {
  constructor() {
    super();
    this.state = {
      isLogin: true
    }
  }
  render() {
    const { isLogin } = this.state;
    let loginText = null;
    if (isLogin) {
      loginText = '欢迎回来~'
    } else {
      loginText = '请先登录~'
    }
    return (
      <div>
        {/* 方案一:使用 if 判断 */}
        <h2>{loginText}</h2>
        {/* 方案二:使用三目运算符 */}
        <button onClick={e => this.loginChange()}>{isLogin ? '退出' : '登录'}</button>
        <hr />
        {/* 方案三:使用逻辑与 && */}
        {isLogin && <h2>同学,你好~</h2>}
      </div >
    )
  }
  loginChange() {
    this.setState({
      isLogin: !this.state.isLogin
    })
  }
}

五、获取 DOM 元素(ref)

import React, { PureComponent, createRef } from 'react'

class App extends PureComponent {
  constructor(props) {
    super(props);
    this.titleRef = createRef();
    this.titleEl = null;
  }
  render() {
    return (
      <div>
        <h2 ref="titleRef">Hello React</h2>
        <h2 ref={this.titleRef}>Hello React</h2>
        <h2 ref={el => this.titleEl = el}>Hello React</h2>
        <button onClick={() => this.changeText()}>改变文本</button>
      </div>
    );
  }
  changeText() {
    // 方式一:通过 refs 获取 DOM 元素
    this.refs.titleRef.innerHTML = '你好 React'
    // 方式二:通过对象 createRef() 获取 DOM 元素
    this.titleRef.current.innerHTML = '你好 JavaScript'
    // 方式三:通过回调函数获取 DOM 元素
    this.titleEl.innerHTML = '你好 HTML'
  }
}

ref 的值根据节点的类型而有所不同:

  • 当 ref 属性用于 HTML 元素时,构造函数中使用 React.createRef() 创建的 ref 接收底层 DOM 元素作为其 current 属性;
  • 当 ref 属性用于自定义 class 组件时,ref 对象接收组件的挂在实例作为其 current 属性;
  • 不能在函数组件上使用 ref 属性,因为函数组件没有实例;

六、受控组件和非受控组件

受控组件:

import React, { PureComponent } from 'react';

class App extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      username: '',
      password: '',
      valid: ''
    }
  }
  render() {
    const { username, password, valid } = this.state;
    return (
      <div>
        <form onSubmit={(e) => this.handleSubmit(e)}>
          <div>
            <label htmlFor="username">
              用户:<input type="text" id="username" name="username" value={username} onChange={(e) => this.handleChange(e)} />
            </label>
          </div>
          <div>
            <label htmlFor="password">
              用户:<input type="password" id="password" name="password" value={password} onChange={(e) => this.handleChange(e)} />
            </label>
          </div>
          <div>
            <label htmlFor="valid">
              用户:<input type="number" id="valid" name="valid" value={valid} onChange={(e) => this.handleChange(e)} />
            </label>
          </div>
          <input type="submit" />
        </form>
      </div>
    );
  }
  // 用户输入后,通过 handleChange 更新 state 中的值
  handleChange(e) {
    this.setState({
      [e.target.name]: e.target.value
    })
  }
  handleSubmit(e) {
    e.preventDefault();
    console.log(this.state);
  }
}
export default App;

非受控组件:

import React, { PureComponent, createRef } from 'react';

class App extends PureComponent {
  constructor(props) {
    super(props);
    this.username = createRef();
  }
  render() {
    return (
      <div>
        <form onSubmit={e => this.handleSubmit(e)}>
          <label htmlFor="username">
            用户:<input type="text" ref={this.username} />
          </label>
          <input type="submit" />
        </form>
      </div>
    );
  }
  // 通过 ref 获取表单元素的 value 值
  handleSubmit(e) {
    e.preventDefault();
    console.log(this.username.current.value);
  }
}
export default App;

七、脚手架文件列表

image.png
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 创建组件引入文件 提供 react reactdom对象 帮助浏览器解析jsx组件名一定要大写 let Compo...
    soo伟阅读 1,048评论 0 2
  • React,用于构建用户界面的 JavaScript 库,是Facebook公司的开源项目,用于开发单页面应用; ...
    hellomyshadow阅读 336评论 0 0
  • React是一个用于构建用户界面的JavaScript库 一、基础知识学习 1. JSX JSX是一个JavaSc...
    Mstian阅读 805评论 0 2
  • 脚手架工具:create-react-app JSX的本质: javascript + xml是一种语法糖(动态创...
    babyface_fe阅读 331评论 0 0
  • React 基础学习总结 1、创建虚拟DOM对象的两种方式 React.createElement(type, p...
    豆腐先生就是我阅读 492评论 0 1

友情链接更多精彩内容