我有一个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'>
有什么建议吗?
答案 0 :(得分:3)
是的,您可以有条件地传递道具,试试这个。
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'>
答案 1 :(得分:2)
您可以通过以太方式实现它。
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;