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

如何访问父组件中子组件的引用,第1张

如何访问父组件中子组件的引用 推荐用于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文档中的转发参考。



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5642293.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存