我想通过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组件,如下所示:
sayHello()
<div className="hello">{ this.props.sayHello() } I'm <Link to="/life">Marco</Link>! Welcome to my hood.</div>
更换:
<Route path="/life" render={props => <Life sayHello = {this.sayHello()} />} />
与
<Route path="/life" render={props => <Life sayHello = {this.sayHello} />} />
错误道具收到sayHello()函数调用的结果,而不是函数本身。