通过 React Router 传递函数 [英] Pass a function through React Router

查看:38
本文介绍了通过 React Router 传递函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过 React Router 将一个函数传递给子组件.我尝试了以下方法,但似乎不起作用.

class App 扩展组件 {构造函数(道具){超级(道具)}使成为() {返回 (<div className="应用程序"><div className="内容"><div className="center-wrapper"><开关><路由精确路径="/" component={Welcome}/><Route path="/life" render={props =><Life sayHello = {this.sayHello()}/>}/></开关>

);}}导出默认应用程序;

我想在 Life 组件中调用 sayHello() 如下:

<div className="hello">{ this.props.sayHello() } 我是 <Link to="/life">Marco</Link>!欢迎来到我的引擎盖.</div>

解决方案

替换:

<Life sayHello = {this.sayHello()}/>}/>

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

错误道具接收的是sayHello()函数的调用结果,而不是函数本身.

I want to pass a function to a child component through React Router. I tried the following but it doesn't seem to work.

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;

I wanted to call sayHello() in the Life component as follows:

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

解决方案

Replace:

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

with

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

The mistake props receive the result of call of sayHello() function instead of function itself.

这篇关于通过 React Router 传递函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆