react高阶组件+ref转发的组合使用
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了react高阶组件+ref转发的组合使用,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2041字,纯文字阅读大概需要3分钟。
内容图文
![react高阶组件+ref转发的组合使用](/upload/InfoBanner/zyjiaocheng/1117/84b6356c18264f9da2d3150e57b79159.jpg)
增强组件:
import React from "react"; type propsType = { forwardedRef: any; }; type stateType = {}; export function logProps(WrappedComponent) { class LogProps extends React.Component<propsType, stateType> { componentDidMount() { console.log("props:", this.props); } render() { return <WrappedComponent {...this.props}/>; } } return React.forwardRef((props: any, ref: any) => { return <LogProps {...props} inputRef={ref}></LogProps>; }); }
子组件
import React from "react"; import { logProps } from "./Test1"; type propsType = { inputRef:any }; type stateType = {}; interface Test{ displayName:any } class Test extends React.Component<propsType, stateType> { static displayName: string;//严格模式不声明会报错 constructor(props) { super(props); this.state = {}; } render() { return ( <div> <label>请输入:</label> {/* 使用父组件传递过来的ref声明通过props */} <input type="text" ref={this.props.inputRef} /> </div> ); } } Test.displayName="child"; //本来需要子组件声明的forwardRef如下写法: // return React.forwardRef((props: any, ref: any) => { // return <Test {...props} inputRef={ref}></Test>; // }); //因为使用了高阶函数增强,所以这些东西也放在了高阶函数中使用,这里只是为了说明,父组件调用后ref可以通过HOC组件穿透到子组件使用, //这里要注意的是因为props本来是不能传递ref的所以其实ref的名字应该是forwardRef声明的?所以props点出来的ref名字要和forwardRef下面的命名一样。但是父组件的ref的变量名字可以和这里的不一样 export default logProps(Test);
父组件:
import React from ‘react‘ import Test2 from "./Test2"; type propsType = {}; type stateType = {}; interface Test{ ww:any } interface Test{ displayName:any } class Test extends React.Component<propsType, stateType> { static displayName: string; constructor(props) { super(props); this.state = {}; //父组件创建调用子组件用到的ref this.ww=React.createRef(); } handleClick=()=>{ // debugger console.log((this.ww as any).current.value) } render() { return <div> <Test2 ref={this.ww}></Test2> <button onClick={this.handleClick}>点我</button> </div>; } } Test.displayName="parent" export default Test;
原文:https://www.cnblogs.com/llcdbk/p/13067670.html
内容总结
以上是互联网集市为您收集整理的react高阶组件+ref转发的组合使用全部内容,希望文章能够帮你解决react高阶组件+ref转发的组合使用所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。