2017-07-06 112 views
1

我的應用程序應根據路線呈現大約30000個svg元素。 如果路線類似www.myapp.com/svg-data/person,它應該呈現person.svg。作爲反應組件加載svg dinamically

稍後(相同的路徑),可以修改此svg:添加背景顏色,一些文本或某些預定義的圖層。 我想我應該加載svg作爲反應組件。我正在看圖書館https://github.com/boopathi/react-svg-loader,但我不認爲它真的適合我的目的。

我的最後一個問題是關於獲取SVG數據作爲串並使其返回除其他事物的SVG一個組件內...

我應該建立一個通用組件,呈現自帶作爲參數任何SVG :

componentDidMount() { 
    if (this.props.params.searchText) { 
     this.props.requestSVG(this.props.params.searchText) 
    } 
    } 

    componentWillReceiveProps(nextProps) { 
    if (this.props.params.searchText !== nextProps.params.searchText) { 
     this.props.requestSVG(nextProps.params.searchText) 
    } 
    } 

這部分將呈現類似:

render() { 
    const {svgData, textForSVGData} = this.props 
    let svgText=null 

    if (textForSVGData) { 
    svgText= <text x='250' y='150' font-size='55'> {textForSVGData} </text> 
    } 

    return (
     <svg> 
     {this.props.svgData} 
     {svgText} 
     </svg> 
    ) 

} 

根據道具應該添加文本,或者在需要的任何其他東西。我想念什麼?這是做這件事的好方法嗎?

回答

0

我建議你,一兩件事情:

  • 在單一組件創建每個SVG,這將幫助您找出您的SVG的行爲,樣式,道具等等

  • 使用higher order component創建通用組件,並把它作爲一個代理,以動態的道具傳遞給你的SVG組件,如果需要

  • 關於路由器添加常用的SVG的行爲,你可以有一個映射路由器 - 圖標或直接設置SVG組件作爲路由器組件呈現

SvgRendering的主要目的是與所述給定的道具來充當高階分量和呈現給定的組件。

class SvgRenderer extends React.Component { 
    constructor(props) { 
    super(props); 

    this.state = { invert: true }; 
    this.toggle = this.toggle.bind(this); 
    } 

    toggle() { 
    this.setState({ inverted: !this.state.inverted }); 
    } 

    render() { 
    const { Svg, svgProps } = this.props; 
    const { inverted } = this.state; 

    return (
     <div> 
     <button onClick={this.toggle}>toggle inverted svg</button> 
     <div><Svg {...svgProps} inverted={inverted}/></div> 
     </div> 
    ); 
    } 
} 

同時PlayIcon(SVG的)目的設置自定義樣式,文本,形狀等

const PlayIcon = (props) => { 
    const { className, inverted } = props; 
    const classes = className ? ['icon', 'logo', 'className'] : ['icon', 'logo']; 

    if (inverted) classes.push('inverted'); 

    return (
    <div className={classes.join(' ')}> 
     <svg 
     version="1.1" 
     viewBox="0 0 512 512"> 
     <path d="M256.000,512.000 C114.615,512.000 0.000,397.385 0.000,256.000 C0.000,114.615 114.615,0.000 256.000,0.000 C397.385,0.000 512.000,114.615 512.000,256.000 C512.000,397.385 397.385,512.000 256.000,512.000 ZM151.172,128.000 L151.172,384.000 L406.907,256.000 L151.172,128.000 Z" /> 
     </svg> 
    </div> 
); 
}; 

我是非常通用的這一建議,併爲這些建議,我創建的結果和例如,在這個小提琴實施:

https://jsfiddle.net/69z2wepo/82451/

讓我知道如果你有任何問題。

+0

我正在使用webpack。只是不知道如何將30000個svg組件集成到我的js代碼中! – user2670996