I recently encountered a problem implementing the createElement API.

Problem code

import React from './react';
const style = {border:'3px solid red', margin:'5px'}
let element = (
  <div id='A1' key='A1' style={style}>
    A1
    <div id='B1' key='B1' style={style}>
      B1
      <div id='c1' key='c1' style={style}> C1</div>
      <div id='c2' key='c2' style={style}>C2</div>
    </div>
    <div id='B2' key='B2' style={style}>
      B2
    </div>
  </div>
)
console.log(element);
Copy the code

The output is

To debug the errors, I run the test directly with react. createElement and get the results.

console.log(React.createElement('div',{id:'A1'},'B1'));
Copy the code


The react. createElement function is not called to parse the JSX syntax, but I don’t know why this is happening.

Attach the react.js code:

const ELEMENT_TEXT = Symbol.for('ELEMENT_TEXT') function createElement(type, props, ... children) { return { type, props: { ... props, children: children.map(child => { return typeof child === 'object' ? child : createTextNode(child) }) } } } function createTextNode(textNode) { return { // ELEMENT_TEXT: A1: <div>A1</div> type: ELEMENT_TEXT, props: { text: textNode, children: [] } } }Copy the code