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

jsd*_*rio 5 javascript svg reactjs

我一直在研究SVG和React的数据表示形式,它们似乎很合适。但是React尚不支持SVG,并且https://github.com/facebook/react/issues/2250尚不存在插件。

但是,有一些变通方法,例如dangerouslySetInnerHTML用于某些元素,就我而言,我还找不到。

我想filtercirclesvg元素内使用属性。但是,它不会呈现到DOM中。这是我的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' />
  }
}
Run Code Online (Sandbox Code Playgroud)

和过滤器:

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>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,如果不包装此组件,就无法按原样重复使用(圆形SVG元素),危险地使用SetInnerHTML。现在是否有任何解决方法可以使用此属性(和其他属性)?

谢谢。

pab*_*.pi 2

对于过滤器,您可以使用 CSS 样式作为解决方法,如下所示:

const style = {
  filter: `url(#${app || 'default'})`
}
Run Code Online (Sandbox Code Playgroud)

和返回组件...

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

如果您只想过滤,可以使用纯 CSS。因此,将其添加到 React props 中。