如何解决ReactJS在渲染函数传递不同的属性集
我有一个ReactJS组件:
class OneComponent extends React.Component {
constructor(props_) {
super(props_);
this.width = 600;
this.height = 600;
this.viewBox = "0 0 600 600";
this.preserveAspectRatio = "xMidYMid meet";
this.responsive = true;
}
render () {
let this_ = this;
return (
<div ref={(divElement) => this.divElement = divElement}>
<svg id={this.prefix} width={this.width} height={this.width} xmlndes='http://www.w3.org/2000/svg' xmlnsXlink='http://www.w3.org/1999/xlink'>
<g id="svgContent">
</g>
</svg>
</div>
)
}
}
export default OneComponent;
您可以看到SVG元素具有width和height参数:
<svg id={this.prefix} width={this.width} height={this.width} xmlndes='http://www.w3.org/2000/svg' xmlnsXlink='http://www.w3.org/1999/xlink'>
但是,在组件参数中,我还有另一个属性viewBox和keepAspectRatio用于响应版本。
在这种情况下,SVG元素必须为:
<svg id={this.prefix}viewBox={this.viewBox} preserveAspectRatio={this.preserveAspectRatio} xmlndes='http://www.w3.org/2000/svg' xmlnsXlink='http://www.w3.org/1999/xlink'>
因此,我可以在一种情况下仅传递width和height属性,而在其他情况下仅传递viewBox和preserveAspectRatio。
类似的东西:
this.responsive ? let svgParams = {width: {this.width},height: {this.height}} : let svgParams = {viewBox: {this.viewBox},preserveAspectRatio: {this.preserveAspectRatio}}
和
<svg id={this.prefix} {svgParams} xmlndes='http://www.w3.org/2000/svg' xmlnsXlink='http://www.w3.org/1999/xlink'>
有什么建议吗?
解决方法
是的,您可以有条件地传递道具,试试这个。
const svgParams = this.responsive
? { width: this.width,height: this.height }
: { viewBox: this.viewBox,preserveAspectRatio: this.preserveAspectRatio };
然后使用传播算子将svgParams作为道具传递
<svg {...svgParams} id={this.prefix} xmlndes='http://www.w3.org/2000/svg' xmlnsXlink='http://www.w3.org/1999/xlink'>
,
您可以通过以太方式实现它。
import React from "react";
import "./styles.css";
class OneComponent extends React.Component {
constructor(props_) {
super(props_);
this.width = 600;
this.height = 600;
this.viewBox = "0 0 600 600";
this.preserveAspectRatio = "xMidYMid meet";
this.responsive = true;
}
prepareSvg() {
return this.responsive
? { width: this.width,height: this.height }
: { viewBox: this.viewBox,preserveAspectRatio: this.preserveAspectRatio };
}
render() {
return (
<div ref={(divElement) => (this.divElement = divElement)}>
<svg
id={this.prefix}
{...this.prepareSvg()}
xmlndes="http://www.w3.org/2000/svg"
xmlnsXlink="http://www.w3.org/1999/xlink"
>
<g id="svgContent"></g>
</svg>
<h1>hello</h1>
</div>
);
}
}
export default OneComponent;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。