简体   繁体   English

在reactjs中有条件地将道具传递给组件

[英]passing props to the component conditionally in reactjs

I want to pass a props to the component only after it full fills a certain condition . 我只想在组件完全满足特定条件后才将props传递给组件。 I have this Paper component inside return of render in react. 我有这个Paper组件在react中返回render。 I want to pass the onScroll only when a condition is there. 我只想在有条件的情况下通过onScroll。

<Paper className={classes.root}  onScroll={this.loadMoreClasses}>

What i want to achieve 我想实现的目标

<Paper className={classes.root}  organizationname!==null ?onScroll={this.loadMoreClasses} :null>

want onScroll to happen only when organizationname is not definedthere 希望仅当未定义组织名称时才发生onScroll

You could pass it like this: 您可以像这样通过它:

<Paper
    className={classes.root}
    onScroll={organizationname !== null ? this.loadMoreClasses : null}
/>

That way your Paper component receives the onScroll listener when the organisation name it set, but does not receive it otherwise. 这样,您的Paper组件会在设置组织名称时接收onScroll侦听器,否则不会接收它。 You need to make sure that the Paper component treats the onScroll prop as optional, otherwise you'll get errors from it trying to call a method that doesn't exist. 您需要确保Paper组件将onScroll视为可选onScroll ,否则尝试调用一个不存在的方法时会从中得到错误。

An alternative would be to always provide an onScroll prop and move the condition to your getMoreClasses method, making it do nothing if the organisation name is not set. 一种替代方法是始终提供一个onScroll并将条件移至您的getMoreClasses方法,如果未设置组织名称,则使其不执行任何操作。

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

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