使用反应渲染时如何访问现有的dom元素?

时间:2018-07-15 23:32:10

标签: javascript reactjs

我将React组件渲染到现有网站中,其根元素的示例可能是:

<div id="root"></div>

我想做的是访问根元素内的任何html,例如:

<div id="root">Hello world</div>

文档seems to indicate可以按照以下步骤进行:

  

ReactDOM.render()不会修改容器节点(仅修改   容器的子代)。可能会插入一个   组件添加到现有DOM节点,而不会覆盖现有   孩子们。

我尝试使用refs进行访问,但是我无法访问这些子DOM元素,有人知道我该如何实现吗?

<div id="root" ref="root">Hello world</div>

1 个答案:

答案 0 :(得分:2)

不幸的是,这在ReactDOM 直接中是不可能的。

<div id="root">中的“ Hello world”字符串被视为容器节点的子代,因此被覆盖。

相反,在调用ReactDOM的.innerHTML方法之前,您需要从div获得root并获得render() ID的let root = document.getElementById("root"); let existingContent = root.innerHTML; ReactDOM.render(yourReactComponent, root); console.log(existingContent); // Do whatever you need to do with this 。然后,您可以随后执行任何操作:

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/posts/new/

Django Version: 1.11
Python Version: 3.6.6
Installed Applications:
   ['django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.humanize',
    'bootstrap3',
    'accounts',
    'groups',
    'posts']

Installed Middleware:
  ['django.middleware.security.SecurityMiddleware',
  'django.contrib.sessions.middleware.SessionMiddleware',
  'django.middleware.common.CommonMiddleware',
   'django.middleware.csrf.CsrfViewMiddleware',
   'django.contrib.auth.middleware.AuthenticationMiddleware',
   'django.contrib.messages.middleware.MessageMiddleware',
  'django.middleware.clickjacking.XFrameOptionsMiddleware']

Template error:
In template E:\Private\django_project\social_clone\simplesocial\templates     \base.html, error at line 10
 __str__ returned non-string (type NoneType)   1 : <!DOCTYPE html>
 2 : {% load staticfiles %}
 3 : <html>
 4 :   <head>
 5 :     <meta charset="utf-8">
 6 :     <title>Egy Social</title>
 7 :     <!-- Latest compiled and minified CSS -->
 8 : 
 9 : 
 10 :     <link rel="stylesheet" href="https: //maxcdn.bootstrapcdn.com /bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
 11 : 
 12 : 
 13 :         <!-- Optional theme -->
 14 : 
 15 :     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
 16 :         <!-- Latest compiled and minified JavaScript -->
 17 :     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
 18 :     <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
 19 :     <link rel="stylesheet" href="{% static 'simplesocial/css/master.css'%}">
 20 :   </head>


 Traceback:

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\core\handlers\exception.py" in inner
 41.response = get_response(request)

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\core\handlers\base.py" in _get_response
 217.response = self.process_exception_by_middleware(e, request)

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\core\handlers\base.py" in _get_response
 215.               response = response.render()

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\template\response.py" in render
 107.             
  self.content = self.rendered_content

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\template\response.py" in rendered_content
 84.         
 content = template.render(context, self._request)

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\template\backends\django.py" in render
 66.            
  return self.template.render(context)

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\template\base.py" in render
 207.                 
 return self._render(context)

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\template\base.py" in _render
 199.   
  return self.nodelist.render(context)

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\template\base.py" in render
  990.          
   bit = node.render_annotated(context)

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\template\base.py" in render_annotated
  957.         
 return self.render(context)

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\template\loader_tags.py" in render
  177.       
  return compiled_parent._render(context)

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\template\base.py" in _render
  199.     
 return self.nodelist.render(context)

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\template\base.py" in render
  990.         
    bit = node.render_annotated(context)

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\template\base.py" in render_annotated
  957.       
  return self.render(context)

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\template\loader_tags.py" in render
   177.       
  return compiled_parent._render(context)

  File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\template\base.py" in _render
   199.      
  return self.nodelist.render(context)

  File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\template\base.py" in render
   990.        
    bit = node.render_annotated(context)

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\template\base.py" in render_annotated
   957.        
 return self.render(context)

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\template\loader_tags.py" in render
   72.          
   result = block.nodelist.render(context)

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\template\base.py" in render
   990.          
   bit = node.render_annotated(context)

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\template\base.py" in render_annotated
  957.       
  return self.render(context)

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\template\loader_tags.py" in render
  72.         
  result = block.nodelist.render(context)

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\template\base.py" in render
  990.         
  bit = node.render_annotated(context)

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\template\base.py" in render_annotated
 957.         
 return self.render(context)

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\template\library.py" in render
  203.   
  output = self.func(*resolved_args, **resolved_kwargs)

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\bootstrap3\templatetags\bootstrap3.py" in bootstrap_form
  338.  
  return render_form(*args, **kwargs)

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\bootstrap3\forms.py" in render_form
  53.
 return renderer_cls(form, **kwargs).render()

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\bootstrap3\renderers.py" in render
   87.  
   return mark_safe(self._render())

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\bootstrap3\renderers.py" in _render
  230.  
   return self.render_errors(self.error_types) + self.render_fields()

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\bootstrap3\renderers.py" in render_fields
   194.       
      bound_css_class=self.bound_css_class,

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\bootstrap3\forms.py" in render_field
 69.  
 return renderer_cls(field, **kwargs).render()

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\bootstrap3\renderers.py" in render
  87.         return mark_safe(self._render())

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\bootstrap3\renderers.py" in _render
  551.         html = self.field.as_widget(attrs=self.widget.attrs)

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\forms\boundfield.py" in as_widget
   120.             **kwargs

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\forms\widgets.py" in render
  220.         context = self.get_context(name, value, attrs)

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\forms\widgets.py" in get_context
 665.         context = super(Select, self).get_context(name, value, attrs)

 File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\forms\widgets.py" in get_context
  627.         context['widget']['optgroups'] = self.optgroups(name, context['widget']['value'], attrs)

  File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\forms\widgets.py" in optgroups
  574.         for option_value, option_label in chain(self.choices):

  File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\forms\models.py" in __iter__
  1118.             yield self.choice(obj)

  File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\forms\models.py" in choice
  1124.         return (self.field.prepare_value(obj), self.field.label_from_instance(obj))

  File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\forms\models.py" in label_from_instance
  1189.         return force_text(obj)

  File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\utils\encoding.py" in force_text
  76.                     s = six.text_type(s)

 Exception Type: TypeError at /posts/new/
 Exception Value: __str__ returned non-string (type NoneType)