javascript - 无法在父组件中运行子组件方法

标签 javascript reactjs

我必须在父组件中运行子组件方法。这不是官方的,但我需要为复杂的代码运行它......我尝试使用 refs 但它在父组件中不起作用。出现以下错误。

Cannot read property 'renderSetup' of undefined

父组件:

class Parent extends Component {
  constructor(props) {
    super(props);
    this._renderSetup = this._renderSetup.bind(this);
  }

  componentDidMount() {
    this._renderSetup();
  }


  _renderSetup() {
    this.refs.Child.renderSetup();
  }

  render() {
    return (
      <Child ref={Child} />
    )
  }

子组件

class Child extends Component {
  constructor(props) {
    super(props);
    this.renderSetup = this.renderSetup.bind(this);
  }

  renderSetup = () => {
     // complicated code
  }

最佳答案

ref 属性是一种特殊属性,您无法通过 props 访问它。要在组件上使用 ref,您可以用 React.forwardRef() 将其包装起来。 :

const { Component, createRef } = React;

class _Child extends Component {
  constructor(props, ...args) {
    super(props, ...args);
    
    if(props.forwardedRef) {
      props.forwardedRef.current = {
        renderSetup: this.renderSetup
      };
    }
  }

  renderSetup = () => {
     console.log('renderSetup');
  }
  
  render() {
    return <div>Child</div>;
  }
}

const Child = React.forwardRef((props, ref) => (
  <_Child {...props} forwardedRef={ref} />
));

class Parent extends Component {
  childRef = createRef();

  componentDidMount() {
    this._renderSetup();
  }


  _renderSetup = () => {
    if(this.childRef.current) {
      this.childRef.current.renderSetup();
    }
  }

  render() {
    return (
      <Child ref={this.childRef} />
    )
  }
}

ReactDOM.render(
  <Parent />,
  root
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

关于javascript - 无法在父组件中运行子组件方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59895234/

相关文章:

reactjs - React hooks - 当对象集合中的嵌套属性发生更改时触发 useEffect

javascript - 发布的 npm 包不应用样式

javascript - 可能的 React 反模式 : Setting initial state from props

javascript - 在 php 中使用 javascript 的 HTML 似乎有冲突

javascript - HTML DOM 元素全局范围

android - 无法运行 "ANY"React Native 示例项目

reactjs - react 只在加载时调用方法一次

javascript - 无法在 IE 中更改 SVG innerHTML

javascript - 您可以将 html 文件渲染到容器中吗?

javascript - 我可以将参数传递给 gulp 任务吗?