通过 React Router 传递函数

IT技术 reactjs react-router
2021-05-16 14:08:17

我想通过 React Router 将函数传递给子组件。我尝试了以下但它似乎不起作用。

class App extends Component {
  constructor(props) {
      super(props)
  }

  render() {
    return (
      <div className="App">
          <div className="content">
          <div className="centered-wrapper">
            <Switch>
              <Route exact path="/" component={Welcome} />
              <Route path="/life" render={props => <Life sayHello = {this.sayHello()} />} />
            </Switch>
          </div>                
      </div>
    );
  }
}

export default App;

我想sayHello()按如下方式调用Life 组件:

<div className="hello">{ this.props.sayHello() } I'm <Link to="/life">Marco</Link>! Welcome to my hood.</div>
2个回答

代替:

<Route path="/life" render={props => <Life sayHello = {this.sayHello()} />} />

<Route path="/life" render={props => <Life sayHello = {this.sayHello} />} />

错误 props 接收sayHello()函数调用的结果而不是函数本身。

您不是传递函数,而是调用它并将返回的结果作为 prop 传递。

sayHello    // function object
sayHello()  // function call, evaluates to return

去掉括号:

render={props => <Life sayHello={this.sayHello} />}

将来,请查看您在控制台中看到的任何错误,并将它们添加到您的问题中。如果您尝试调用sayHelloLife组件,您肯定会看到与此类似的错误:

Uncaught TypeError: undefined is not a function

有了这些信息,您就可以自己找到问题,或者让任何试图提供帮助的人都更清楚:)