所以我才开始学习React,这是我正在研究的第一个状态示例。

这是代码:-

<div id="app"></div>
<script src="https://npmcdn.com/[email protected]/dist/react.js"></script>
<script src="https://npmcdn.com/[email protected]/dist/react-dom.js"></script>
<script>

    //main render
    ReactDOM.render(
        React.createElement(TextAreaCounter, {text: 'Bob'}),
        document.getElementById("app")
    );

    //create component now
    var TextAreaCounter = React.createClass({

        propTypes: {
            text: React.propTypes.string,
        },

        getDefaultProps: function() {
            return {
                text: '',
            };
        },

        render: function(){
            return React.DOM.div(null,
                React.DOM.textarea({
                    defaultValue: this.props.text,
                }),
                React.DOM.h3(null, this.props.text.length)
            );
        }

    });

</script>


这是控制台中的错误:

react.js:20150 Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.
    at invariant (react.js:20150)
    at ReactCompositeComponentWrapper.instantiateReactComponent [as _instantiateReactComponent] (react.js:18327)
    at ReactCompositeComponentWrapper.performInitialMount (react.js:6256)
    at ReactCompositeComponentWrapper.mountComponent (react.js:6139)
    at Object.mountComponent (react.js:13787)
    at mountComponentIntoNode (react.js:11873)
    at ReactReconcileTransaction.perform (react.js:16987)
    at batchedMountComponentIntoNode (react.js:11895)
    at ReactDefaultBatchingStrategyTransaction.perform (react.js:16987)
    at Object.batchedUpdates (react.js:10324)


我在这里做什么错?我试图找到一些解决方案,以解决在控制台中收到的错误,但是没有任何帮助。对此会得到一些专家的评论将是很棒的。

最佳答案

我认为,您需要先定义TextAreaCounter,然后使用ReactDOM.render呈现TextAreaCounter组件。

原因是,在TextAreaCounterReactDOM.render值中呈现TextAreaCounter时,将是undefined,如果将该变量定义为let而不是var,则会引发错误:


  未定义TextAreaCounter


仅仅因为var,您没有收到该错误,我建议您也阅读letvar之间的区别。选中此answer

像这样写,它将起作用,运行以​​下代码段:



<div id="app"></div>
<script src="https://npmcdn.com/[email protected]/dist/react.js"></script>
<script src="https://npmcdn.com/[email protected]/dist/react-dom.js"></script>
<script >

     var TextAreaCounter = React.createClass({

          getDefaultProps: function() {
              return {
                  text: '',
              };
          },

          render: function() {
              return React.DOM.div(null,
                 React.DOM.textarea({
                    defaultValue: this.props.text,
                 }),
                 React.DOM.h3(null, this.props.text.length)
              );
          }
     });

     ReactDOM.render(
          React.createElement(TextAreaCounter, {text: 'Bob'}),
          document.getElementById("app")
     );

</script>

关于javascript - react 无状态的例子,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43518792/

10-09 22:13