[英]in React, how to call a function living in another component?
在我的反应App.js
的return
我目前正在以一种有效的方式调用this.searchVenues()
,但它很凌乱,我知道还有更好的方法。 searchVenues()
函数位于App.js
,我有一些按钮需要位于其自己的组件中,然后只需<ButtonComponent/>
而不是:
render() {
return (
<div className="App container-fluid">
<Navbar/>
<div className="row">
<div className="col-xs-3">
<button onClick ={() => this.searchVenues("yoga+coffee", "5")}>5</button>
<button onClick ={() => this.searchVenues("yoga+coffee", "10")}>10</button>
<button onClick ={() => this.searchVenues("yoga+coffee", "15")}>15</button>
<SideBar {...this.state} handleListItemClick={this.handleListItemClick}/>
</div>
<div className="col-md-9 full-height">
<Map {...this.state}
handleMarkerClick={this.handleMarkerClick}/>
</div>
</div>
<Footer/>
</div>
);
}
但是当我这样做this.searchVenues("yoga+coffee", "5")
无法正常工作,这是可以理解的。 什么是使其最佳或更好的方法? 如何从另一个文件(组件)访问该功能?
我相信您想在App.js组件中声明您的searchVenues函数,如下所示:
searchVenues = (arg1, arg2) => {here is the body of your function}
...并使用道具将其传递给ButtonComponent:
<ButtonComponent searchVenues={this.searchVenues}
一旦进入无状态ButtonComponent,就可以在其中创建一个新函数,如果要避免渲染中使用匿名函数( 您可以在此处阅读 )
const searchVenues = (arg1, arg2) => {
return event => {props.searchVenues(arg1, arg2);}
}
...并将其添加到onClick事件:
<button onClick ={searchVenues('coffee+yoga', props.value)}>{props.value}</button>
如果您希望按钮位于另一个组件中,但又从另一个组件接收处理程序,则可以通过props传递它们。
import React, { Component } from 'react'
import MyButton from './MyButton'
export default class App extends Component {
buttonClickHandler= () => {
alert('I have been clicked!')
}
render = () => (
<MyButton onClickHandler={this.buttonClickHandler} />
)
}
这是MyButton组件文件:
import React from 'react'
const MyButton = (props) => (
<button onClick={props.onClickHandler}>Click Me for an Alert!</button>
)
export default MyButton
你既可以有searchVenues
在定义ButtonComponent
或将其传递给ButtonComponent
作为道具。 然后,在ButtonComponent
渲染函数中,您将执行相同的操作:
<button onClick ={() => this.searchVenues("yoga+coffee", "15")}>15</button>
或者如果它作为道具被传递
<button onClick ={() => this.props.searchVenues("yoga+coffee", "15")}>15</button>
我还要补充一点,@ Bryan关于服务绝对正确。 例如,假设您在名为Product的数据库中有一个表。 好吧,您不想在需要产品列表的每个组件中实现getAllProducts()
。 相反,您将创建一个名为ProductService的类,其中将定义getAllProducts()
。 然后,对于需要产品列表的任何组件,您将导入ProductService类并调用ProductService.getAllProducts()
。
希望能有所帮助。
如果要从任何组件执行方法,并且这些方法的结果将更改应用程序的全局状态,则可以从使用actions
受益。 无论您使用的是flux还是redux体系结构,都可以从应用程序的任何部分触发操作,并在全局状态下执行更改,此更改将反映在侦听此状态的任何组件上。
https://reactjs.org/blog/2014/07/30/flux-actions-and-the-dispatcher.html https://redux.js.org/basics/actions
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.