2016-09-29 44 views
2

我正在使用帶有React的FlowRouter/Meteor,並試圖將FlowRouter.go方法傳遞給響應按鈕以在按下按鈕時導航到新頁面。我想這樣做是爲了將按鈕保留爲可重用組件,但我正在努力弄清楚如何將FlowRouter.go方法傳遞給無狀態功能組件。這是我現在所擁有的一個簡化版本:如何將外部方法傳遞給React中的無狀態功能組件

import React, { Component } from 'react'; 
import { FlowRouter } from 'meteor/kadira:flow-router'; 

const ParentComponent =() => { 
    // define text and styles here 
    return (
    <div> 
     <Button text={text} style={styles} action={FlowRouter.go("Register")}/> 
    </div> 
); 
} 

,然後我的按鈕組件:

import React, { Component } from 'react'; 

// Call to action button 
const Button = ({text, style, action}) => { 
    return (
    <button className="btn" style={style} onClick={() => action()}> 
     {text} 
    </button> 
); 
} 

Button.propTypes = { 
    text: React.PropTypes.string.isRequired, 
    style: React.PropTypes.object, 
    action: React.PropTypes.func 
}; 

Button.defaultProps = { 
    text: "A button.", 
    style: { 
    height: "100%", 
    width: "100%", 
    }, 
    action: null 
}; 

export default Button 

有誰知道什麼語法要求爲反應的官能組件加載第三方庫的方法?

回答

5

您需要傳入一個函數。您實際上是通過調用FlowRouter.go("Register")執行FlowRouter.go函數。

試試這個:

const ParentComponent =() => { 
    // define text and styles here 
    return (
    <div> 
     <Button text={text} style={styles} action={() => FlowRouter.go("Register")}/> 
    </div> 
); 
} 

也...作爲action是一個功能,您可以直接傳遞到您的onClick,像這樣:

<button className="btn" style={style} onClick={action}> 
+0

你是我的新最愛的人。我想它與該函數在何處/如何執行有關。謝謝! – bgmaster

相關問題