zoukankan      html  css  js  c++  java
  • react学习(三)之生命周期/refs/受控组件 篇

    挂载/卸载

    //在类组件中
    class Clock extends React.Component {
      constructor(props) {
        super(props);
        this.state = {date: new Date()};
      }
    
      componentDidMount() {  //挂载
        this.timerID = setInterval(
          () => this.tick(),
          1000
        );
      }
    
      componentWillUnmount() {  // 卸载
        clearInterval(this.timerID);
      }
    
      tick() {
        this.setState({
          date: new Date()
        });
      }
    
      render() {
        return (
          <div>
            <h1>Hello, world!</h1>
            <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
          </div>
        );
      }
    }

    refs

    当需要操作DOM节点时候,可以使用ref,但是,尽量避免至今操作DOM。使用refs场景有:

    • 处理focus、文本选择或者媒体播放
    • 触发强制动画
    • 集成第三方DOM库

    使用方法:

    ref 属性接受回调函数,并且当组件 装载(mounted) 或者 卸载(unmounted) 之后,回调函数会立即执行。

    class CustomTextInput extends React.Component {//ref只能在类组件中使用
      constructor(props) {
        super(props);
        this.focus = this.focus.bind(this);
      }
    
      focus() {
        // 通过使用原生API,显式地聚焦text输入框
        this.textInput.focus();  //使用这个DOM引用方式。
      }
    
      render() {
        // 在实例中通过使用`ref`回调函数来存储text输入框的DOM元素引用(例如:this.textInput)
        return (
          <div>
            <input
              type="text"
              ref={(input) => { this.textInput = input; }} /> //在挂载时候,执行该函数,该函数返回 input DOM引用。
            <input
              type="button"
              value="Focus the text input"
              onClick={this.focus}
            />
    
          </div>
        );
      }
    }

    受控组件与不受控组件

    受控组件,用在表单元素中,数据保存在组件的state中,并只能通过setstate()来更新。state成为‘单一数据源原则’

    不受控组件,不使用state,表单数据由DOM元素处理。可以使用ref来获得DOM引用。因为不受控组件的数据来源是 DOM 元素。例如:

    class NameForm extends React.Component {
      constructor(props) {
        super(props);
        this.handleSubmit = this.handleSubmit.bind(this);
      }
    
      handleSubmit(event) {
        alert('A name was submitted: ' + this.input.value);
        event.preventDefault();
      }
    
      render() {
        return (
          <form onSubmit={this.handleSubmit}>
            <label>
              Name:
              <input type="text" ref={(input) => this.input = input} />
            </label>
            <input type="submit" value="Submit" />
          </form>
        );
      }
    }
  • 相关阅读:
    Delphi 与 C/C++ 数据类型对照表
    JAVA中堆和栈的区别
    关于Column '*' not found 解决方案 Hibernate使用SQL查询返回实体类型,即返回某个类,或实体类
    Oracle笔记
    oracle时间运算
    struts2中iterator标签的相关使用
    url传中文,转码
    表格的css,细线表格
    使用struts 2 获取服务器数据 ongl表达式 标签
    struts 2 Commons FileUpload文件上传
  • 原文地址:https://www.cnblogs.com/yadiblogs/p/9214660.html
Copyright © 2011-2022 走看看