簡體   English   中英

在React中,如何調用另一個組件中的函數?

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

在我的反應App.jsreturn我目前正在以一種有效的方式調用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM