1. 程式人生 > 其它 >react當中refs

react當中refs

Refs 提供了一種方式,允許我們訪問 DOM 節點 或 在 render 方法中建立的 React 元素(元件)。

Refs主要提供了三種方式:

import React, { Component } from 'react'

import { Input } from 'antd';

import Refs1 from "./refsComponents/refs1"


//方式1:字串字面量 (即將棄用,不推薦, 潛在bug問題)

// class Refs extends Component {
//     componentDidMount(){
//         console.log(this.refs.zujian,this.refs.dom,this.refs.ant,"方式1");
// } // render() { // return ( // <div style={{background:"#ccc",padding:"10px"}}> // <h4>react 當中refs三種使用方式。</h4> // <Refs1 ref="zujian"/> // <input type="text" placeholder="請輸入" ref="dom"/> // <Input placeholder="antDesign input" ref="ant"/>
// </div> // ) // } // } //------------------------------------------------------------------------------------------------- //方式2:函式引數賦值(一般給元件實力本身) // class Refs extends Component { // componentDidMount(){ // console.log(this.zujian,this.dom,this.ant,"方式2"); // } // render() {
// return ( // <div style={{background:"#ccc",padding:"10px"}}> // <h4>react 當中refs三種使用方式。</h4> // <Refs1 ref={zujian=>this.zujian = zujian}/> // <input type="text" placeholder="請輸入" ref={dom=>this.dom = dom}/> // <Input placeholder="antDesign input" ref={ant=>this.ant = ant}/> // </div> // ) // } // } //------------------------------------------------------------------------------------------------- //方式3:新API(createRef),官方推薦使用。 class Refs extends Component { zujian = React.createRef() dom = React.createRef() ant = React.createRef() componentDidMount(){ console.log(this.zujian.current,"方式3"); console.log(this.dom.current,"方式3"); console.log(this.ant.current,"方式3"); } render() { return ( <div style={{background:"#ccc",padding:"10px"}}> <h4>react 當中refs三種使用方式。</h4> <Refs1 ref={this.zujian}/> <input type="text" placeholder="請輸入" ref={this.dom}/> <Input placeholder="antDesign input" ref={this.ant}/> </div> ) } } export default Refs;