Check if property exists using React.js

前端 未结 6 1741
悲哀的现实
悲哀的现实 2020-12-29 21:42

I\'m new to using react.js, and am trying to write a re-usable component that has an optional property passed to it. In the component, that optional property pulls data from

相关标签:
6条回答
  • 2020-12-29 22:14

    I suggest to try this elegant solution to check callback property on your component:

    if(typeof this.props.onClickCallback === 'function') { 
    // Do stuff; 
    }
    

    or applying destructuring:

    const { onClickCallback } = this.props;
    if(typeof onClickCallback === 'function') { 
    // Do stuff; 
    }
    
    0 讨论(0)
  • 2020-12-29 22:17

    This works for me

    if(this.props.test === undefined){
        console.log('props.test is not defined')
    }
    
    0 讨论(0)
  • 2020-12-29 22:22

    what is the prop in question? how about

    {this.props.propInQuestion ? <a href="#">link</a> : null}
    
    0 讨论(0)
  • 2020-12-29 22:30

    You need to return out of getParentTaskLink() with the link you need.

     if (current_task.parent_task) {
          return (<a href="#">link</a>);
        } else { return null; }
    
    0 讨论(0)
  • 2020-12-29 22:35

    I figured this out. Apparently it was a syntax issue - you need to use a string when searching for properties in objects. The line below works:

    if ('parent_task' in current_task)
    
    0 讨论(0)
  • 2020-12-29 22:35

    Check if a property exists using React.js

    There are two options you can use. the && operator and If statement to check if the props exist. Option 1 will check if the property exists then run the second part of the code. It works like an if without the if.

    Option 1

    this.props.property && this.props.property
    

    Option 2

    if(this.props.property){
    this.props.property
    }
    

    This also works with function names.

    You can use this also check to render components and tags.

    0 讨论(0)
提交回复
热议问题