繁体   English   中英

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

[英]How to pass an external method to a stateless functional component in React

我在React中使用FlowRouter / Meteor,并试图将FlowRouter.go方法传递给react按钮,以在按下按钮时导航到新页面。 我想这样做是为了将按钮保留为可重复使用的组件,但仍在努力找出如何将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>
  );
}

然后是我的按钮组件:

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

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

您需要传递一个函数。 您实际上是通过调用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}>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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