reactjs – React组件中的条件属性?
发布时间:2020-12-15 20:16:32 所属栏目:百科 来源:网络整理
导读:我刚才做出反应,我只是写了一些丑陋的代码.有人能告诉我更好的方法吗?这是伪代码: 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.
我刚才做出反应,我只是写了一些丑陋的代码.有人能告诉我更好的方法吗?这是伪代码:
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>的属性.元素只有当反应组件收到它的道具时.但是,并非所有反应组件的道具都是属性,其中一些可能是属于innerHTML的this.props.text. 必须有一个不那么冗长的方式来写我想要的东西? 解决方法
所以,你不需要使用if条件.相反,您可以检查value属性,如果没有获取值,则返回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忽略这些属性. 希望能帮助到你! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |