标签:回调 直接 class export str from turn imp nbsp
ref是React提供的用来操纵React组件实例或者DOM元素的接口。
ref可以作用于:
React组件的实例
1 class AutoFocusTextInput extends React.Component { 2 constructor(props) { 3 super(props); 4 this.textInput = React.createRef(); 5 } 6 7 componentDidMount() { 8 this.textInput.current.focusTextInput(); 9 } 10 11 render() { 12 return ( 13 <CustomTextInput ref={this.textInput} /> 14 ); 15 } 16 }
Dom元素
1 class MyComponent extends React.Component { 2 constructor(props) { 3 super(props); 4 this.myRef = React.createRef(); 5 } 6 render() { 7 return <div ref={this.myRef} />; 8 } 9 }
React组件有两种定义方式:
将ref回调函数作用于某一个React组件,此时回调函数会在当前组件被实例化并挂载到页面上才会被调用。
ref回调函数被调用时,会将当前组件的实例作为参数传递给函数。
首先,能够使用ref的child Component必然是一个类,如果要实现,必然要破坏child component的封装性,直接到child component中获取其中DOM。
1 class App extends Component { 2 constructor(props) { 3 super(props); 4 this.getDOM = this.getDOM.bind(this); 5 } 6 7 getDOM(element) { 8 this.div = element 9 } 10 11 render() { 12 return ( 13 <div> 14 <Button getDOM={this.getDOM} /> 15 </div> 16 ); 17 } 18 } 19 //Button.js 20 export default (props) => ( 21 <div> 22 <button ref={props.getDOM} onClick={props.onClick}>this is a button</button> 23 </div> 24 )
1 //APP.js 2 class App extends Component { 3 constructor(props) { 4 super(props); 5 this.handleClick = this.handleClick.bind(this); 6 this.div = React.createRef() 7 } 8 9 render() { 10 return ( 11 <div> 12 <Button ref={this.div}/> 13 </div> 14 ); 15 } 16 } 17 //Button.js 18 import React, {Component} from ‘react‘; 19 20 export default class Button extends Component { 21 constructor(props) { 22 super(props); 23 this.button = React.createRef(); 24 this.getButton = this.getButton.bind(this); 25 } 26 27 getButton() { 28 return this.button 29 } 30 31 render() { 32 return ( 33 <div> 34 <button ref={this.button}>this is a button</button> 35 </div> 36 ); 37 } 38 }
标签:回调 直接 class export str from turn imp nbsp
原文地址:https://www.cnblogs.com/jack-wangsir/p/13096687.html