2016-09-29 119 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

相关问题