gpt4 book ai didi

reactjs - 通过 React Router 传递函数

转载 作者:行者123 更新时间:2023-12-03 13:20:08 24 4
gpt4 key购买 nike

我想通过 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;

我想在 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() 函数的调用结果,而不是函数本身。

关于reactjs - 通过 React Router 传递函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44116467/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com