[英]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.