如何将外部方法传递给React中的无状态功能组件

bgm*_*ter 2 javascript meteor reactjs flow-router

我使用FlowRouter /流星有反应,我想传递一个FlowRouter.go方法的反应按钮,按下按钮时,浏览到一个新的一页.我想这样做是为了保持按钮作为可重复使用的组件,但我在努力搞清楚如何通过FlowRouter.go方法为无状态的功能组件.这是我现在拥有的简化版本:

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>
  );
}
Run Code Online (Sandbox Code Playgroud)

然后我的按钮组件:

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
Run Code Online (Sandbox Code Playgroud)

有谁知道将方法从第三方库加载到React功能组件需要什么语法?

ctr*_*usb 5

你需要传递一个函数.您实际上是FlowRouter.go通过调用执行该函数FlowRouter.go("Register").

试试这个:

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

另外......作为action一个函数你可以直接将它传递给你的onClick,如下所示:

<button className="btn" style={style} onClick={action}>
Run Code Online (Sandbox Code Playgroud)