简体   繁体   English

在React中,如何调用另一个组件中的函数?

[英]in React, how to call a function living in another component?

in my react's App.js 's return i am currently calling this.searchVenues() in a way that works but is messy and i know there is a better way. 在我的反应App.jsreturn我目前正在以一种有效的方式调用this.searchVenues() ,但它很凌乱,我知道还有更好的方法。 The searchVenues() function lives in App.js and I have buttons that need to be in their own component, then just <ButtonComponent/> instead of: 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>
    );
  }

but when i do this.searchVenues("yoga+coffee", "5") does not work, understandably so. 但是当我这样做this.searchVenues("yoga+coffee", "5")无法正常工作,这是可以理解的。 What's the best or a better way to make it work? 什么是使其最佳或更好的方法? How do i access the function from another file ( component )? 如何从另一个文件(组件)访问该功能?

I believe you want to declare your searchVenues func in App.js component like this: 我相信您想在App.js组件中声明您的searchVenues函数,如下所示:

searchVenues = (arg1, arg2) => {here is the body of your function}

... and pass it down to the ButtonComponent using props: ...并使用道具将其传递给ButtonComponent:

<ButtonComponent searchVenues={this.searchVenues}

Once you are in your stateless ButtonComponent, you can create a new function inside it if you want to avoid anonymous functions in your render ( you can read on it here ) 一旦进入无状态ButtonComponent,就可以在其中创建一个新函数,如果要避免渲染中使用匿名函数( 您可以在此处阅读

const searchVenues = (arg1, arg2) => { 
    return event => {props.searchVenues(arg1, arg2);}
}

... and add it to the onClick event: ...并将其添加到onClick事件:

<button onClick ={searchVenues('coffee+yoga', props.value)}>{props.value}</button>

If you want your buttons to live in another component, but receive handlers from another component, you can pass them down through props. 如果您希望按钮位于另一个组件中,但又从另一个组件接收处理程序,则可以通过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} />
    )
}

And here is the MyButton component file: 这是MyButton组件文件:

import React from 'react'

const MyButton = (props) => (
    <button onClick={props.onClickHandler}>Click Me for an Alert!</button>
)

export default MyButton

You could either have searchVenues defined in your ButtonComponent or pass it to ButtonComponent as a prop. 你既可以有searchVenues在定义ButtonComponent或将其传递给ButtonComponent作为道具。 Then in your ButtonComponent render function you would do the same thing: 然后,在ButtonComponent渲染函数中,您将执行相同的操作:

<button onClick ={() => this.searchVenues("yoga+coffee", "15")}>15</button>

or if it is passed as a prop 或者如果它作为道具被传递

<button onClick ={() => this.props.searchVenues("yoga+coffee", "15")}>15</button>

I will also add that @Bryan is absolutely right about services. 我还要补充一点,@ Bryan关于服务绝对正确。 Lets say for instance you have a table in a database called Product . 例如,假设您在名为Product的数据库中有一个表。 Well, you don't want to implement getAllProducts() in every component that needs a list of products. 好吧,您不想在需要产品列表的每个组件中实现getAllProducts() Instead, you would create a class called ProductService where getAllProducts() would be defined. 相反,您将创建一个名为ProductService的类,其中将定义getAllProducts() Then, for any component that needs a list of products, you would import the ProductService class and call ProductService.getAllProducts() . 然后,对于需要产品列表的任何组件,您将导入ProductService类并调用ProductService.getAllProducts()

Hope that helps. 希望能有所帮助。

If you want to execute methods from any component, and the result of those methods will change the global state of the app, you might benefit from using actions . 如果要从任何组件执行方法,并且这些方法的结果将更改应用程序的全局状态,则可以从使用actions受益。 Whether you're using flux or redux architecture, actions can be triggered from any part of the app, and perform changes in the global state, this changes will be reflected on any component that is listening to this state. 无论您使用的是flux还是redux体系结构,都可以从应用程序的任何部分触发操作,并在全局状态下执行更改,此更改将反映在侦听此状态的任何组件上。

https://reactjs.org/blog/2014/07/30/flux-actions-and-the-dispatcher.html https://redux.js.org/basics/actions 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM