ref 的使用

2022-05-12  本文已影响0人  张_何
创建 ref的方式
传入字符串(过期)
export default class App extends PureComponent {
  render() {
    return (
      <div>
        <h2 ref="titleRef">Hello React</h2>
        <button onClick={e => this.changeText()}>改变文本</button>
      </div>
    )
  }

  changeText() {
    this.refs.titleRef.innerHTML = "Hello Coderwhy";
  }
}
传入一个对象(推荐)
import React, { PureComponent, createRef, Component } from 'react';
export default class App extends PureComponent {
  constructor(props) {
    super(props);
    this.titleRef = createRef();
  }

  render() {
    return (
      <div>
        <h2 ref={this.titleRef}>Hello React</h2>
        <button onClick={e => this.changeText()}>改变文本</button>
      </div>
    )
  }

  changeText() {
    this.titleRef.current.innerHTML = "Hello JavaScript";
  }
}
传入一个函数
import React, { PureComponent, createRef, Component } from 'react';
export default class App extends PureComponent {
  constructor(props) {
    super(props);
    this.titleEl = null;
  }

  render() {
    return (
      <div>
        <h2 ref={arg => this.titleEl = arg}>Hello React</h2>
        <button onClick={e => this.changeText()}>改变文本</button>
      </div>
    )
  }

  changeText() {
    this.titleEl.innerHTML = "Hello TypeScript";
  }
}

ref 的类型

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

// 高阶组件forwardRef
const Profile = forwardRef(function(props, ref) {
  return <p ref={ref}>Profile</p>
})

export default class App extends PureComponent {
  constructor(props) {
    super(props);
    this.profileRef = createRef();
  }

  render() {
    return (
      <div>
        <Profile ref={this.profileRef} name={"why"}/>
        <button onClick={e => this.printRef()}>打印ref</button>
      </div>
    )
  }

  printRef() {
    console.log(this.profileRef.current);
  }
}

应用

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

class Counter extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      counter: 0
    }
  }

  render() {
    return (
      <div>
        <h2>当前计数: {this.state.counter}</h2>
        <button onClick={e => this.increment()}>+1</button>
      </div>
    )
  }

  increment() {
    this.setState({
      counter: this.state.counter + 1
    })
  }
}

export default class App extends PureComponent {
  constructor(props) {
    super(props);
    this.counterRef = createRef();
  }

  render() {
    return (
      <div>
        <Counter ref={this.counterRef}/>
        <button onClick={e => this.appBtnClick()}>App按钮</button>
      </div>
    )
  }
  appBtnClick() {
    this.counterRef.current.increment();
  }
}
上一篇下一篇

猜你喜欢

热点阅读