React中的Refs属性怎么用(react,refs,开发技术)

时间:2024-04-28 18:24:44 作者 : 石家庄SEO 分类 : 开发技术
  • TAG :

    1 介绍

    react组件的三大属性:

    1.props属性:封装传递给组件的参数

    2.state属性:组件的状态,当值发生改变后,重新渲染组件

    3.refs属性:

    (1)通过该属性可以去访问DOM元素或render函数中的react元素(虚拟的DOM元素) ——DOM元素或render函数中的react元素的代理(句柄)

    (2)本质是ReactDOM.render()函数返回的实例(组件实例或DOM节点)

    Refs在计算机中称为弹性文件系统。React中的Refs提供了一种方式,允许我们访问DOM节点或在render方法中创建的React元素。本质为ReactDOM.render()返回的组件实例,如果是渲染组件则返回的是组件实例,如果渲染dom则返回的是具体的dom节点。

    作用:Refs时React提供给我们安全访问DOM元素或者某个组件实例的句柄。在类组件中,React将ref属性中第一个参数作为DOM中的句柄。在函数组件中,React用hooks的api useRef也能获得ref。

    2 使用方法

    2.1 createRef(版本>=React16.3)

    一般在构造函数中将refs分配给实例属性,以供组件的其他方法中使用。

    1、对于html元素:可以获取元素实例

    示例代码:

    classRefsextendsReact.Component{constructor(props){super(props);//在构造函数中初始化一个ref,然后在return中就可以使用了this.myRef=React.createRef();console.log(this.myRef);}componentDidMount(){//在render()函数执行完成后调用this.myRef.current.innerHTML="橘猫吃不胖";//this.myRef中有一个current属性}render(){return(<div>{/*如果ref属性被用于html,那么它的值就是底层DOM元素*/}<divref={this.myRef}></div></div>);}}

    React中的Refs属性怎么用

    2、可以和类组件进行绑定 &mdash;&mdash; 代表类组件的实例

    示例代码:

    classRefsextendsReact.Component{constructor(props){super(props);this.myRef=React.createRef();}componentDidMount(){//在父组件中调用了子组件的方法this.myRef.current.change();}render(){return<Childrenref={this.myRef}/>}}classChildrenextendsReact.Component{change(){console.log("橘猫吃不胖变身");}render(){return<span>橘猫吃不胖</span>}}

    2.2 回调Refs

    React将在组件挂载时,会调用ref回调函数并传入DOM怨怒是,当卸载时调用它并传入null。早componentDidMount或componentDidUpdate触发前,React会保证refs一定是最新的。

    示例代码:

    classRefsextendsReact.Component{constructor(props){super(props);this.targetRef=null;this.myRef=(e)=>this.targetRef=e;}componentDidMount(){console.log("this.refs"+this.refs.container);}render(){return<divref={this.myRef}>橘猫吃不胖</div>}}

    2.3 String类型的Refs(已过时,不推荐使用)

    示例代码:

    classRefsextendsReact.Component{constructor(props){super(props);this.targetRef=null;this.myRef=(e)=>this.targetRef=e;}componentDidMount(){console.log("this.refs"+this.refs.container);}render(){return<divref={this.myRef}>橘猫吃不胖</div>}}

    2.4 useRef(React Hooks)

    functionHookRef(props){constinputElement=useRef();return(<div><inputref={inputElement}/><buttononClick={()=>{inputElement.current.focus()}}>获得焦点</button></div>)}
     </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
    本文:React中的Refs属性怎么用的详细内容,希望对您有所帮助,信息来源于网络。
    上一篇:ASP.NET Core如何使用Log4net实现日志记录功能下一篇:

    9 人围观 / 0 条评论 ↓快速评论↓

    (必须)

    (必须,保密)

    阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18