【问题标题】:Incorrect casing error with dynamically rendered component in ReactReact 中动态渲染组件的大小写错误
【发布时间】:2018-05-23 21:16:52
【问题描述】:

所以,我想以后有空,想做一个动态生成的页面。出于这个原因,我想从一个对象中读取组件数据,如下所示:

  layout: {
    toolbar: {
      components: [
        {
          type: "Testcomp",
          theme: "default",
          data: "div1"
        },
        {
          type: "Testcomp",
          theme: "pro",
          data: "div2"
        },
      ]}}

组件将被动态导入、启用/激活,除此之外,这是应该动态呈现组件的 jsx 代码:

render() {
    const toolbarComponents = userSession.layout.toolbar.components.map(Component => (
      <Component.type theme={Component.theme} data={Component.data} key={this.getKey()} />
    ));

    return (
      <div>
        <div className="toolbar">
          toolbar
          {toolbarComponents}
        </div>
    . . .
      </div>
    );
  }

但是我在 Chrome 的 devtool 中收到以下警告,该组件也没有显示:

警告:使用了不正确的大小写。对 React 组件使用 PascalCase,对 HTML 元素使用小写。

警告:此浏览器无法识别标签。如果您打算渲染一个 React 组件,请以大写字母开头。

我的代码有什么问题?

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

您收到这些错误是因为您没有在此处引用组件本身,而是使用字符串作为名称。因此,也许您需要考虑另一种方法来动态创建组件。就像从一个基础组件开始,只给它一些道具和数据。

// Define above main component or elsewhere then import.
const MyComponent = ( props ) => <div>{props.data}</div>

// Main component
render() {
  const toolbarComponents = userSession.layout.toolbar.components.map(
    component => <MyComponent theme={component.theme} data={component.data} />
  );

  return <div className="App">{toolbarComponents}</div>;
}

这里我们不再使用类型键。如果你想像这样使用不同的组件,你可以创建每个基础组件,然后使用类型键而不是字符串作为其名称,直接引用组件。

【讨论】:

  • 是的,首先我的问题是我只引用了一个字符串而不是一个对象。至于建议的替代解决方案,这是一个好主意,但要另当别论。
【解决方案2】:

我尝试使用与您相同的方法,其中我使用字符串按名称引用 React 组件。但是,它似乎并未设计为在标准标签之外使用,例如 div

相反,对我有用的是导入我想要显示的组件,然后将其设置为状态。

import MyComponent from 'mycomponent';

class Parent extends React.Component {
  constructor() {
    super();
    this.state = {
      selectedComponent: null
    };
  }

  render() {
    return (
      <div className="Parent">
        <h2>Parent Component</h2>
        <button onClick={() => this.setState({ selectedComponent: MyComponent })}>Show my component</button>
          {this.state.selectedComponent !== null && React.createElement(this.state.selectedComponent, null, null)}
        </div>
    );
  }
}

【讨论】:

    猜你喜欢
    • 2014-12-18
    • 2022-01-25
    • 2020-02-28
    • 1970-01-01
    • 1970-01-01
    • 2015-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多