【问题标题】:React.js: Passing nested props into React.createElementReact.js:将嵌套道具传递给 React.createElement
【发布时间】:2015-05-25 14:10:47
【问题描述】:

我有表单的代码

props = { user: {userattr1: 1, userattr2: 2}};
var element = React.createElement(MyReactClass, props);

也就是说,props 是一个嵌套对象。当我尝试编译上面的代码时,我得到了错误:

警告:任何键控对象的使用都应该在作为子对象传递之前包装在 React.addons.createFragment(object) 中。

我一直在网上寻找,似乎嵌套对象完全可以用作道具。如何解决我的错误?

编辑:MyReactClass 看起来像这样:

var MyReactClass = React.createClass({
  render: function () {
    <div>{this.props.user}</div>
  }
})

【问题讨论】:

  • 你得到的不是错误而是警告
  • 你能在 jsfiddle 中重现这个吗?我认为您的问题出在其他地方,而不是道具。 MyReactClass 是如何定义的?

标签: javascript reactjs


【解决方案1】:

我不认为你遇到的问题与作为道具的嵌套对象有关。这是一个例子:

var Hello = React.createClass({
    render: function() {
        return <div>Hello {this.props.user.name}</div>;
    }
});

var props = { user: {name: "World"}};
React.render(React.createElement(Hello, props), document.getElementById('container'));

https://jsfiddle.net/urjmndzk

更有可能,您的问题与您如何设置子组件的键有关。但是,如果不查看整个代码,就很难判断。

这是creeateFragment 函数的链接,它可能会对您有所帮助。 https://facebook.github.io/react/docs/create-fragment.html

【讨论】:

  • 事实证明,问题在于我试图在 HTML 标记中使用一个对象,假设 React 将使用它的 JSON 表示。
【解决方案2】:

如果您使用的是 JSX,您还可以通过这样构建对象来传递嵌套对象作为道具:

<HelloWorldClass user={{name:'Kyle'}} />

堆栈片段中的语法示例

// function component syntax
function HelloWorldFunc(props) {
  return (
    <div>Hello, {props.user.name} </div>
  );
}
// class component syntax
class HelloWorldClass extends React.Component {
  render() {
    return (
      <div >
        Hello, {this.props.user.name}
      </div>
    );
  }
}

// createElement syntax
const helloCreate = React.createElement(HelloWorldFunc, {user:{name:'Kyle'}});
// JSX syntax
const helloJSX = <HelloWorldClass user={{name:'Kyle'}} />

ReactDOM.render(
  <div>
    {helloCreate}
    {helloJSX}
  </div>
,document.querySelector("#root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

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

【讨论】:

    猜你喜欢
    • 2017-10-03
    • 2018-03-12
    • 2017-10-20
    • 2019-10-16
    • 1970-01-01
    • 2021-07-12
    • 2021-12-07
    • 2015-08-18
    • 1970-01-01
    相关资源
    最近更新 更多