react父组件调用子组件方法

305 阅读1分钟

其一,调用HOC组件(是子组件)方法

import React from 'react';
// 高阶组件
const withRef = WrappedComponent => {
  class HOC extends React.PureComponent {
    constructor(props) {
      super(props);
      this.wrappedInstance = null;
    }
    getWrappedInstance() {
      return this.wrappedInstance;
    }
    render() {
      // 将ref传递给被包装的组件
      return <WrappedComponent ref={instance => this.wrappedInstance = instance} {...this.props} />;
    }
  }
  // 使用React.forwardRef来转发ref
  return React.forwardRef((props, ref) => {
    return <HOC {...props} forwardedRef={ref} />;
  });
};

// 被包装的组件
const MyComponent = React.forwardRef((props, ref) => {
  return <div ref={ref}>{props.text}</div>;
});
 
// 应用高阶组件
const MyComponentWithRef = withRef(MyComponent);
 
class App extends React.Component {
  componentDidMount() {
    // 在这里可以访问MyComponent的实例
    console.log(this.myComponentInstance);
  }
  render() {
    // 使用高阶组件,并通过ref获取实例
    return (
      <MyComponentWithRef
        text="Hello, World!"
        ref={instance => this.myComponentInstance = instance}
      />
    );
  }
}
export default App;

常规方法

import React, { forwardRef, useImperativeHandle } from 'react';
 
const ChildComponent = forwardRef((props, ref) => {
  const handleClick = () => {
    console.log('ChildComponent clicked!');
  };
 
  useImperativeHandle(ref, () => ({
    handleClick
  }));
 
  return (
    <button onClick={handleClick}>点击</button>
  );
});
 
export default ChildComponent;

eact 不允许组件访问其他组件的 DOM 节点。甚至自己的子组件也不行!这是故意的。Refs 是一种脱围机制,应该谨慎使用。手动操作 另一个 组件的 DOM 节点会使你的代码更加脆弱。

const MyInput = forwardRef((props, ref) => {  
return <input {...props} ref={ref} />;  
});