【发布时间】:2020-07-17 20:02:54
【问题描述】:
我是 React 新手,所以这可能很明显,但我不能通过 prop 传递给从其父级创建组件的函数。
我可以将 props 传递给子组件,但同样不适用于函数。
我有<Subscription>,我可以像这样从它的父post传递参数:
<Subscription auth={auth} stripeAmount={post.amount} stripePlanId={post.planid}/>
这将创建一个 Stripe 订阅。我想将订阅限制为订阅stripePlanId,我通过以下方式订阅:
class Subscription extends React.Component {
// https://stripe.com/docs/checkout#integration-custom
componentDidMount() {
this.stripeCheckout = window.StripeCheckout.configure({
...etc...
email: this.props.auth.email,
})
}
newSubscription = () => {
var stripePlanId = this.props.stripePlanId;
this.stripeCheckout.open({
amount: this.props.stripeAmount, // in cents
description: this.props.stripePlanId,
token: function(token){
createSubscription(token, stripePlanId)
}
})
}
..etc..
这很好用。但是现在要通过 stripePlanId 我不知道如何通过 stripePlanId 因为它是通过函数呈现的 - 这个 {children} 参数似乎只在函数中传递,并且尝试添加参数会导致错误,他们不是它期望对传递的参数起作用的函数:
const FireflySubscription = ({children}) => (
<FirebaseAuth>
{ ({isLoading, error, auth}) => {
if (error || isLoading || !auth) {
//it pushes these arguments to the parent function
return children({
error,
isLoading,
subscription: null,
})
}
// the issue - how to populate this?
const stripePlanId = ""
// when working this should return the subscription for only this planId
if (stripePlanId) {
return <FirestoreCollection
path="subscriptions"
filter={[['createdBy', '==', auth.uid], ['stripePlanId','==', stripePlanId]]}
>
{ ({error, isLoading, data}) => {
return children({
error,
isLoading,
subscription: data.length > 0 ? data : null,
})
}}
</FirestoreCollection>
}
return <FirestoreCollection
path="subscriptions"
filter={['createdBy', '==', auth.uid]}
>
{ ({error, isLoading, data}) => {
return children({
error,
isLoading,
subscription: data.length > 0 ? data : null,
})
}}
</FirestoreCollection>
}}
</FirebaseAuth>
)
export default FireflySubscription
我试过用另一种方法通过,但是“作用域”没有通过:
getPostSubscriptions = stripePlanId => {
return <FireflySubscription>
// it gets these arguments from FireflySubscription function above
{ ({error, isLoading, subscription}) => {
if (error) {
return <Error error={error} />
}
if (isLoading) {
return <p>loading...</p>
}
if (!subscription) {
return <div>
<p><strong>Subscribe to get paid features</strong></p>
..etc...
</div>
}
..etc...
}}
</FireflySubscription>
}
render() {
return this.getPostSubscriptions(this.props.stripePlanId)
}
}
非常感谢任何线索!我正在改编的原始代码来自https://github.com/sampl/firefly,如果有帮助的话。
【问题讨论】:
-
对不起,我看不出这有什么帮助:)
-
我认为这篇文章可能对您有所帮助How to pass props to {this.props.children}
标签: javascript reactjs components react-props