首页 > 解决方案 > 无法在父组件中运行子组件方法

问题描述

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

无法读取未定义的属性“renderSetup”

父组件:

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
  }

标签: javascriptreactjs

解决方案


如果你需要调用一个孩子的方法,你可能需要重新考虑你的解决方案......

在 React 中,数据在层次结构中传输,如下所示:

Parent ---(props)--> Child

Parent <--(events)-- Child

您的组件应该基于某种状态呈现输出 HTML,而不是来自函数的调用

但是,以下内容非常受欢迎:

Parent --> calls some function

function --> changes some state

Child --> renders the content based on that state

这可以使用Redux 或 ContextAPI来完成,您可以在其中存储全局状态,在您想要的任何组件中对其进行更改,并且正在侦听该全局状态的子组件在状态更改时重新呈现。

但是,如果您不想使用 Redux 或 ContextAPI,则可以使用普通道具:

父组件:

class Parent extends Component {
    state = {
        renderChildSetup: false
    }

    handleSomeEvent: () => {
        this.setState({ renderChildSetup: true });
    }

    render () {
        return <Child renderSetup={this.state.renderChildSetup} />
    }
}

子组件:

class Child extends Component {
    render () {
        return (
            <div>

                ...

                this.props.renderSetup ? <Setup /> : null

                ...

            </div>
        )
    }
}

推荐阅读