来自其他组件React

时间:2018-11-06 07:55:26

标签: javascript reactjs meteor

我创建了一个顶部栏菜单,该菜单需要访问react组件。在topbar文件中,我不渲染其他组件,但是想访问我使用的其中一个组件中的函数。

项目结构如下:

Header Component
TopBar Component
LayoutWrapper Component <-- Here I render other components
  CustomerDetails Component <-- Here sits the functon I want to call.

这是TopBar文件:

class AdminTopbar extends Component   {
  renderTopMenu() {

    ...

    if (currentPage.projects || currentPage.customers || currentPage.activities) {
        return(
            <nav>
                ...

                <li>
                    // Function needs to be called here
                    {menuPageType == null ? null : <button onClick={updateActivityCardDetails.bind(this)}>Archiveren</button>}

                </li>
            </nav>
        );          
    }`enter code here`
}
render() {
    return (
        <div className="topbar clear">

        ...

        </div>
    );
  }
}
export default withRouter(AdminTopbar);

函数所在的ActivityCardDetails文件:

class ActivityCardDetails extends Component {
  constructor(props){
    super(props);

    // set page title
    document.title = 'Strippenkaarten overzicht';
  }

  updateActivityCardDetails() {

  }
}

我找到了一些有关给父对象的引用的帖子,但这些文件之间没有嵌套结构。

回顾一下:在TopBar组件(这是一个没有任何关系的独立组件)上,我想调用位于ActvityCardDetails组件中的updateActivityCard方法。

2 个答案:

答案 0 :(得分:2)

React最近(已添加了上下文API)https://reactjs.org/docs/context.html

您最好将功能分解到组件之外,因为该功能由严格层次结构无关的不同组件使用。然后只需使用上下文从每个组件访问它即可。

答案 1 :(得分:0)

您可以尝试使用包装器组件包装整个结构,并按照下面每一行给出的说明进行操作:

Wrapper Component <-- Here place a state and a custom function that can set a callbackFunction to its state e.g. myFunc = (callback) => this.setState({updateFunction: callback}) 
  Header Component
  TopBar Component <-- Pass the Wrapper Component's state here through props, like state={this.state}
  LayoutWrapper Component <-- Pass the Wrapper Component's custom function here through props
    CustomerDetails Component <-- Pass the Wrapper Component's custom function here through its parent's props, and call it like 'this.props.myFunc(this.yourInnerUpdateFunction)' on DidMount

完成此操作后,您应该可以通过“ this.props.state.updateFunction()”从TopBar组件调用updateFunction()

P.S。这不是理想的方法,但是如果您的应用程序不太繁重,则可以完成工作。希望这会有所帮助。

相关问题