在动态创建的React组件上设置自定义道具

时间:2016-11-02 03:10:02

标签: javascript reactjs

我重构了一些我的React代码,以便在我无法直接使用Babel的地方(例如在页面上使用简短的嵌入式JavaScript)中使用。为了帮助解决这个问题,我设置了一个简短的函数来构建组件并将道具传递给它们。这段代码很好用:

components.js

import ResponsiveMenu from './components/responsive-menu';
window.setupMenu = (items, ele) => {
  ReactDOM.render(<ResponsiveMenu items={items}/>, ele);
}; 

静电js.html

<div id="menu"></div>
<script>
   setupMenu({ items: [] }, document.getElementById('menu');
</script>

然而,当我试图将它变成更通用的东西来处理更多这样的组件时:

components.js

import ResponsiveMenu from './components/responsive-menu';
import AnotherComp from './components/another-comp';

window.setupComponent = (selector, name, props) => {
  let eles;

  if (typeof selector == 'string') {
    eles = [];
    let nl = document.querySelectorAll(selector), node;
    for (let i = 0; node = nl[i]; i++) { eles.push(node); }
  } else {
    eles = $.toArray(selector); // A helper function that converts any value to an array.
  }

  return eles.map (
    (ele) => {
      let passProps = typeof props == 'function' ? props(ele) : props;
      return ReactDOM.render(React.createElement(name, passProps), ele);
    }
  );
};

静电js.html

<div id="menu"></div>
<script>
   setupComponent('#menu', 'ResponsiveMenu', { items: [] });
</script>

然后我收到此错误:Warning: Unknown prop "items" on <ResponsiveMenu> tag. Remove this prop from the element. For details, see (really unhelpful shortened link that SO doesn't want me posting)

请帮助我理解为什么这适用于JSX版本,而不是更适合创建组件的手动版本。

1 个答案:

答案 0 :(得分:4)

当您将字符串参数传递给React.createElement时,它将创建本机DOM元素,并且没有有效的html DOM ResponsiveMenu

您可以将元素存储到哈希并将其存储到window变量中。

示例:

// store component into window variable
window.components = {
     ResponsiveMenu: ResponsiveMenu
}

//extract component from window variable by name
React.createElement(window.components[name], passProps)