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>
    );
  }
}

 

posted @ 2018-06-22 17:49  迪迪的博客  阅读(403)  评论(0编辑  收藏  举报