简体   繁体   English

在React.js中使用SVG过滤器属性

[英]Use SVG filter attribute in React.js

I have been researching a bit on data representation with SVG and React and they seem a perfect fit. 我一直在研究SVG和React的数据表示,它们看起来非常合适。 However SVG is not yet supported in React, and an addon does not exist yet https://github.com/facebook/react/issues/2250 . 但是React尚不支持SVG,并且还不存在插件https://github.com/facebook/react/issues/2250

Yet there is some workarounds like using dangerouslySetInnerHTML for some elements, in my case I cannot find one yet. 然而,有一些解决方法,比如对某些元素使用dangerouslySetInnerHTML ,在我的情况下我还找不到一个。

I want to use filter attribute inside a circle svg element. 我想在circle svg元素中使用filter属性。 However It gets not rendered into the DOM. 但是它没有被渲染到DOM中。 Here it is my React Component: 这是我的React组件:

class DeviceDot extends React.Component {
  render () {
    const { app, idx } = this.props

    return  <circle cx={50 * idx} cy={50 * idx} r='25' filter={`url(#${app})`} fill='mediumorchid' />
  }
}

And the filter: 和过滤器:

class FilterSVG extends React.Component {
  render () {
    const { app, idx } = this.props
    const icon = app ? `/api/apps/${app}/logo` : '/img/dflt.png'

    return (
      <filter id={app || 'default'} x='0%' y='0%' width='100%' height='100%'>
        <feImage xlinkHref={icon} />
      </filter>
    )
  }
}

However I cannot use dangerouslySetInnerHTML without wrapping this component, which I want to reuse as is (a circle SVG element). 但是我不能在不包装这个组件的情况下使用dangerouslySetInnerHTML,我想按原样重用它(一个圆形的SVG元素)。 Is there any work around to use this attribute (and others) you are using right now? 是否有任何解决方法可以使用您现在使用的此属性(以及其他属性)?

Thank you. 谢谢。

For filter you can use CSS styles as workaround, like this: 对于过滤器,您可以使用CSS样式作为解决方法,如下所示:

const style = {
  filter: `url(#${app || 'default'})`
}

And the returning component... 而返回的组件......

return <circle cx={50 * idx} cy={50 * idx} r='25' style={style} />

If you only want to filter you can use plain CSS. 如果您只想过滤,可以使用纯CSS。 Thus, add it to React props. 因此,将它添加到React道具。

React does support SVG. React 确实支持SVG。 The issue you've linked to has been fixed. 您已链接到的问题已修复。 In some cases the JSX attribute will be different to the HTML attribute, eg xlinkHref instead of xlink:href . 在某些情况下,JSX属性将与HTML属性不同,例如xlinkHref而不是xlink:href It should not be necessary to use dangerouslySetInnerHTML . 没有必要使用dangerouslySetInnerHTML

In the code above, it looks as if you're simply using the wrong variable. 在上面的代码中,看起来好像只是使用了错误的变量。 You want this instead: 你想要这个:

filter={`url(#${icon})`}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM