使用React Factory的组件未被渲染

时间:2018-05-02 19:35:36

标签: reactjs

我使用React Factory尝试了这个简单的组件,但浏览器中的输出是空白的。我做错了什么?

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pure React Samples</title>
</head>
<body>

<!-- Target Container -->
<div id="react-container"></div>
<! -- React Library & React DOM -->
<script src="https://unpkg.com/react@15.4.2/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@15.4.2/dist/react-dom.js"></script>
<script>
    const simpleComponent = () => React.DOM.h1(null, 'Baked Salmon')

    const myfactory = React.createFactory(simpleComponent)

    ReactDOM.render(myfactory,document.getElementbyId("react-container"))
</script>
</body>
</html>

编辑此代码可以正常运行而无需将组件转换为元素。

const IngredientsList = (list) => React.DOM.h1(null, 'Baked Salmon')

const Ingredients = React.createFactory(IngredientsList)

const list = {}

ReactDOM.render(Ingredients(list), document.getElementById('react-container'))

我错过了什么?

1 个答案:

答案 0 :(得分:1)

您的代码存在两个问题。

  1. document.getElementbyId更改为document.getElementById
  2. ReactDOM.render函数需要React element,但React.createFactory会返回一个组件。所以你需要将该组件转换为元素。您可以使用React.createElement功能

    const simpleComponent = () => React.DOM.h1(null, 'Baked Salmon')
    
    const myfactory = React.createFactory(simpleComponent)
    
    ReactDOM.render(React.createElement(myfactory) ,document.getElementbyId("react-container"))
    
  3. https://jsfiddle.net/m19k4p08/