【问题标题】:React render not working with createElement反应渲染不适用于 createElement
【发布时间】:2016-05-22 22:24:35
【问题描述】:

我的简单组件:

var AddProductForm = React.createClass({
    render: function(){
        return(
            <form >
                <input type='text' placeholder='lablbalbalbal'/>
            </form>
        )
    }
})

我想通过 onClick 在某个确定的 div 中“渲染”第一个组件的第二个组件:

var HeaderAction = React.createClass({
    render: function(){
        return(
            <button type="button" onClick={this.handleClick}  className="btn border-slate text-slate-800 btn-flat"><i className={this.props.icon + " position-left"}></i>{this.props.name}</button>
        )
    },
    handleClick: function(){
        var component = React.createElement(this.props.action.component);
        ReactDOM.render( component, document.getElementById('content'));
    }
})

当我单击“HeaderAction”组件时,出现错误:

未捕获的不变违规:无效标签:

我的“组件”中的 console.log():

Object {$$typeof: Symbol(react.element), type: "<AddProductForm/>", key: null, ref: null, props: Object…}
$$typeof: Symbol(react.element)
_owner: null
_self: null
_source: null
_store: Object
key: null
props: Object
ref: null
type: "<AddProductForm/>"
__proto__: Object

如果在渲染调用中我将“component”更改为“&lt;AddProductForm/&gt;”,它可以正常工作,但在渲染之前使用 createElement 实例化对象则不行。

【问题讨论】:

  • 什么是this.props.action.component?渲染失败的时候?
  • this.props.action.component 解析为字符串,没有失败。

标签: javascript reactjs


【解决方案1】:
var AddProductForm = React.createClass({
    render: function(){
        return(
            <form >
                <input type='text' placeholder='lablbalbalbal'/>
            </form>
        )
    }
})

var HeaderAction = React.createClass({
    render: function(){
        return(
            <button type="button" onClick={this.handleClick}</button>
        )
    },
    handleClick: function(){
        var component = React.createElement(AddProductForm);
        ReactDOM.render( component, document.getElementById('content'));
    }
})
var mount = document.getElementById('container');
ReactDOM.render(React.createElement(HeaderAction), mount)

我没有给你答案,但这似乎有效。我不知道你的情况是什么this.props.action.component。我创造了一个小小提琴。也许我们可以解决这个问题。 https://jsfiddle.net/walkerrsmith/htaca7fa/

【讨论】:

  • 在我的例子中, this.props.action.component 是动态传递的字符串,它引用了我应该渲染的子组件。问题是 createElement 无法以某种方式实例化正确的元素,传递 'HeaderAction ' 甚至 '
  • 这可能有用。继续阅读前几个回复。 github.com/facebook/react/issues/3365。也许评论 github.com/facebook/react/issues/3365#issuecomment-163397564 有帮助
  • 沃克是正确的。 React.createElement 可以接受一个普通元素标签的字符串,或者是 react 组件的类对象。 facebook.github.io/react/docs/glossary.html
  • @CHBuckingham ...此外,如果您错误地提供了一个字符串而不是类对象,React 将尝试使用该名称而不是您的闪亮组件呈现标签。默默。这发生在我身上,因为我不得不在无法使用 JSX 的地方开始渲染,并且不知道如何正确地进行渲染。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多