栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何访问父组件中子组件的引用

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何访问父组件中子组件的引用

推荐用于16.3之前的React版本

如果无法避免,那么从React文档中提取的建议模式将是:

import React, { Component } from 'react';const Child = ({ setRef }) => <input type="text" ref={setRef} />;class Parent extends Component {    constructor(props) {        super(props);        this.setRef = this.setRef.bind(this);    }    componentDidMount() {        // Calling a function on the Child DOM element        this.childRef.focus();    }    setRef(input) {        this.childRef = input;    }    render() {        return <Child setRef={this.setRef} />    }}

家长 转发绑定到一个功能道具 家长

this
。当呼叫作出反应的 儿童的
ref
道具
setRef
也将分配
孩子的
ref
父母的
childRef
财产。

建议用于React> = 16.3

引用转发是一种选择加入功能,它使某些组件可以接收它们收到的引用,并将其进一步向下传递(即“转发”)给孩子。

我们创建 的组件 可以转发他们

ref
React.forwardRef
。返回的 Component ref
prop必须与的返回类型相同
React.createRef
。每当React装入DOM节点
current
时,
ref
创建的with的属性都
React.createRef
将指向基础DOM节点。

import React from "react";const LibraryButton = React.forwardRef((props, ref) => (  <button ref={ref} {...props}>    FancyButton  </button>));class AutoFocus extends React.Component {  constructor(props) {    super(props);    this.childRef = React.createRef();    this.onClick = this.onClick.bind(this);  }  componentDidMount() {    this.childRef.current.focus();  }  onClick() {    console.log("fancy!");  }  render() {    return <LibraryButton onClick={this.onClick} ref={this.childRef} />;  }}

转发参考HOC示例

创建的 组件 将其转发

ref
到子节点。

function logProps(Component) {  class LogProps extends React.Component {    componentDidUpdate(prevProps) {      console.log('old props:', prevProps);      console.log('new props:', this.props);    }    render() {      const {forwardedRef, ...rest} = this.props;      // Assign the custom prop "forwardedRef" as a ref      return <Component ref={forwardedRef} {...rest} />;    }  }  // Note the second param "ref" provided by React.forwardRef.  // We can pass it along to LogProps as a regular prop, e.g. "forwardedRef"  // And it can then be attached to the Component.  return React.forwardRef((props, ref) => {    return <LogProps {...props} forwardedRef={ref} />;  });}

请参阅React文档中的转发参考。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/636434.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号