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

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

本文关键字:状态 组件 功能 React 外部 方法      更新时间:2023-09-26

我正在使用FlowRouter/Meteor与React,我试图通过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}>