简体   繁体   English

如何在React.js中正确处理对象元素

[英]How to properly handle object elements in React.js

I am trying to use the browsers native tooling for creating svg elements within a react component. 我正在尝试使用浏览器的本机工具在react组件内创建svg元素。 The error I get when creating an element and placing that variable in the render method is the following: 创建元素并将该变量放置在render方法中时出现的错误如下:

Objects are not valid as a React child (found: [object Element]) 对象作为React子对象无效(找到:[object Element])

I can get the element to the page with the following but I know it is not the best way. 我可以使用以下内容将元素带到页面,但我知道这不是最好的方法。 What would be the proper way for handling this case? 处理此案的正确方法是什么?

import React from 'react'


export default class Circle extends React.Component {

  componentDidMount() {
    let canvas = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
    canvas.appendChild(document.createElementNS('http://www.w3.org/2000/svg', 'ellipse'))
    document.getElementById('element').appendChild(canvas)
  }

  render() {
    return (
      <div id='element'></div>
    );
  }
}

You can simply use svg and ellipse tag in your code. 您可以在代码中简单地使用svg和ellipse标记。

And here is all supported svg attributes. 是所有受支持的svg属性。

import React from 'react'

export default class Circle extends React.Component {

  render() {
    return (
      <div id='element'>
          <svg></svg>
          <ellipse></ellipse>
      </div>
    );
  }
}

React's SVG support is (almost) at feature parity. React的SVG支持(几乎)在功能奇偶性上。 The error that you got was likely using a javascript object that wasn't a React component. 您收到的错误很可能是使用了不是React组件的javascript对象。 For example, something like this is completely valid: 例如,这样的事情是完全有效的:

class CaretIcon extends React.Component {
  render() {
        return (
         <svg
          xmlns="http://www.w3.org/2000/svg"
          xmlnsXlink="http://www.w3.org/1999/xlink"
          height={100}
          style={{ enableBackground: 'new 0 0 512 512'}}
          version="1.1"
          viewBox="0 0 512 512"
          width={100}
          xmlSpace="preserve">
            <path d="M413.1,327.3l-1.8-2.1l-136-156.5c-4.6-5.3-11.5-8.6-19.2-8.6c-7.7,0-14.6,3.4-19.2,8.6L101,324.9l-2.3,2.6  C97,330,96,333,96,336.2c0,8.7,7.4,15.8,16.6,15.8v0h286.8v0c9.2,0,16.6-7.1,16.6-15.8C416,332.9,414.9,329.8,413.1,327.3z"/>
        </svg>
    )
  }
}

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

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