将函数从父组件传递到子组件

时间:2018-10-22 20:45:09

标签: reactjs typescript

我正在尝试进行单页应用程序导航,因此当用户单击菜单链接时,组件会加载到页面容器中。这是我尝试过的:

App.tsx:

import * as React from 'react';

import Home from './components/Home';
import MainMenu from './components/MainMenu';
import SignUp from './components/SignUp';

interface IProps {
  SignUp?: boolean;
}

interface IState{
  SignUp: boolean;
}

class App extends React.Component<IProps,IState>
{
  constructor(props: IProps, state: IState) {
    super(props);
    this.renderPage = this.renderPage.bind(this);
    this.state = state;
    this.setState({
      SignUp: false
    });
  }

  public renderPage(page: string)
  {
    if(page === 'SignUp')
    {
        this.setState({
          SignUp: true
        });
    }
  }

  public render()
  {
    let page = <Home/>;

    if(this.state.SignUp)
    {
      page = <SignUp/>;
    }

    return (
      <div className="App">
        <MainMenu renderPage={this.renderPage}/>
        <div className="container-fluid">
           {page}
        </div>
      </div>
    );
  }
}

export default App;

MainMenu.tsx:

import * as React from 'react';

import './Home.css';

interface IProps
{
    renderPage: (page: string) => void
}

class MainMenu extends React.Component<IProps> {
  public render() {
    return (
        <nav className="navbar navbar-expand-lg navbar-light bg-light">
            <div className="collapse navbar-collapse" id="navbarSupportedContent">
                <ul className="navbar-nav mr-auto">
                    <li className="nav-item active">
                        <a className="nav-link" href="#" onClick={this.props.renderPage('Home')}>
                            Home
                        </a>
                    </li>
                    <li className="nav-item">
                        <a className="nav-link" href="#" onClick={this.props.renderPage('SignUp')}>
                            Sign Up
                        </a>
                    </li>

                </ul>
            </div>
        </nav>
    );
  }
}

export default MainMenu;

我在MainMenu.tsx中收到此错误:

  

类型'void'不能分配给类型'((event:   MouseEvent)=> void)|未定义”。

1 个答案:

答案 0 :(得分:2)

在MainMenu组件内部,您调用传递的函数,而不是将其关联到一个元素。

<a className="nav-link" href="#" onClick={() => this.props.renderPage('SignUp')}>
    Sign Up
</a>

即使您未传递事件参数,上面的示例也可以解决该错误。

但是,如果您使用react-router会更好,这会根据导航来处理渲染组件吗?