React组件中的条件属性?

时间:2016-10-08 10:56:37

标签: reactjs

我是新手,我只是写了一些丑陋的代码。有人能告诉我更好的方法吗?这是伪代码:

let btn;

if(this.props.href && !this.props.onClick && !this.props.dataMsg etc...)
btn = <a href={this.props.href}>{this.props.text}</a>;


else if(!this.props.href && this.props.onClick && !this.props.dataMsg etc...)
btn = <a onClick={this.props.onClick}>{this.props.text}</a>;

etc...

else if(this.props.href && this.props.onClick && !this.props.dataMsg etc...)
btn = <a href={this.props.href} onClick={this.props.onClick}>{this.props.text}</a>;

else if(!this.props.href && this.props.onClick && this.props.dataMsg etc...)
btn = <a onClick={this.props.onClick} data-msg={this.props.dataMsg}>{this.props.text}</a>;

etc...

换句话说,我只想在反应组件收到它的道具时才设置<a>元素的属性。但是,并非所有反应组件的道具都是属性,其中一些属于this.props.text属于innerHTML。

必须有一种不那么冗长的方式来写我想要的东西?

1 个答案:

答案 0 :(得分:10)

  

React会忽略所有以undefined为其值的属性。

因此,您不需要使用if条件。相反,您可以检查值属性,如果您没有获得该值,则返回undefined

例如:

您可以按如下方式编写代码,

<a
  href={this.props.href} //returns undefined if href not present in props
  onClick={this.props.onClick && this.props.onClick} //set callback if it is present in the props
  data-msg={this.props.dataMsg} //returns undefined if href not present in props
>
 {this.props.text}
</a>;

undefined返回给任何属性会使React忽略这些属性。

希望它有所帮助!

相关问题