react ref 的使用和 react傳送門 Portal 作用以及使用


/* * @Description: ref 的場景和 傳送門 Portal 作用以及使用 * @Version: 2.0 * @Autor: lhl * @Date: 2020-06-01 10:20:33 * @LastEditors: lhl * @LastEditTime: 2020-06-02 14:07:17 */ import React, { Component, useRef } from 'react' import ReactDOM from 'react-dom' export default class App extends Component { render() { return ( <div>
        <p>hello react</p>
        <FunRef abc="111"></FunRef>
        <RefClassComponent></RefClassComponent>
        <CbRef></CbRef>
        <Dialog></Dialog>
      </div> ) } } // 默認情況下,你不能在函數組件上使用 ref 屬性,因為它們沒有實例 // 但是特別的,你可以在函數組件內部使用 ref 屬性,只要它指向一個 DOM 元素或 class 組件 // 如果要在函數組件中使用 ref,你可以使用 forwardRef 或者可以將該組件轉化為 class 組件 function FunRef(props) { console.log(props) // {abc: "111"} // 這里必須聲明 textInput,這樣 ref 才可以引用它 const textInput = useRef(null); function handleClick() { textInput.current.focus(); } return ( <div>
      <input type="text" ref={textInput} />
      <input type="button" value="聚焦" onClick={handleClick} />
    </div> ); } // class 組件中ref的使用 如果你目前還在使用 this.refs.xx 這種方式訪問 refs ,現在建議用回調函數或 createRef API 的方式代替 class RefClassComponent extends Component { constructor(props) { super(props); this.myRef = React.createRef(); } render() { return <div ref={this.myRef} />; } } // 回調函數的方式 訪問 refs React.forwardRef 接受一個渲染函數,其接收 props 和 ref 參數並返回一個 React 節點 class CbRef extends Component { render() { return ( <FunRef inputRef={el => this.inputElement = el} /> ); } } // createPortal 傳送門的使用 Portal 提供了一種將子節點渲染到存在於父組件以外的 DOM 節點的優秀的方案 class Dialog extends React.Component { constructor(props) { super(props); this.el = document.createElement('div'); this.el.setAttribute('class', 'dailog-box'); } componentDidMount() { document.body.appendChild(this.el); } componentWillUnmount() { document.body.removeChild(this.el); } render() { return ReactDOM.createPortal(( <div className="dailog-content"> 彈窗內容 </div> ), this.el); } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM