【问题标题】:How to pass an external method to a stateless functional component in React如何将外部方法传递给 React 中的无状态功能组件
【发布时间】:2016-09-29 14:12:13
【问题描述】:

我将 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 功能组件中需要什么语法?

【问题讨论】:

    标签: javascript reactjs meteor flow-router


    【解决方案1】:

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

    【讨论】:

    • 你是我的新宠。我认为这与函数执行的位置/方式有关。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2017-11-17
    • 2022-12-21
    • 1970-01-01
    • 2019-09-18
    • 2018-01-15
    • 2017-01-26
    • 1970-01-01
    • 2020-07-04
    相关资源
    最近更新 更多