反应 - 将原始 js 数组作为 prop 传递,但 jsx 正在将其修改为 js 对象

react - passing in a raw js array as a prop, but jsx is modifying it into a js object

传入原始数组作为 prop,但它似乎被 React / jsx 修改为一个 json 对象,该对象具有与数组对应的名为“0”、“1”等的键元素。这使得无法判断 prop 实际上是数组还是单个组件。

例如,

MyComponent 有:

   propTypes: {
      attachedComponents: React.PropTypes.oneOfType([React.PropTypes.array, React.PropTypes.object])
   }

实例化MyComponent并传入一个数组:

   var foo = <Foo />  // my custom component 1
   var bar = <Bar />  // my custom component 2
   <MyComponent attachedComponents={[foo, bar]} />

问题是,在 MyComponent 内部,this.props.attachedComponents 不是真正的 JS 数组 -- 它是某种 JS 对象,它具有键“0”、“1”,分别对应传入的数组元素。

这让我无法以编程方式确定它是否是传入的单个组件,或者它是否是一个实际数组,而不做一些非常糟糕的拼凑:

我的组件:

   getInitialState: function() {
        // this cannot work as intended, because the array passed in is converted into a js object whose typeof is object, not array:
        if (typeof this.props.attachedComponents !== 'array') {
            // do code for single component situation
        }
    }

我无法检查 Object.keys(this.props.attachedComponents).length,因为对于传入的单个组件,Object.keys(this.props.attachedComponents) 看起来像这样:

["$$typeof", "type", "key", "ref", "props", "_owner"]

现在,如果您想知道我为什么要传入组件数组,那是因为我想以编程方式添加组件;我看过this.props.children,但是这个好像一点都不靠谱:

Facebook says that this.props.children is opaque, and you must use React.Children api calls, all of which are getters, which seems to imply that this.props.children should not be mutated.

关于如何检测 this.props.attachedComponents 是否是一个数组,而不做一些非常糟糕的拼凑,有什么想法吗?

谢谢

JSX 不对 props 做任何事情。

它实际上只是调用 React.createElement 的语法糖。 Your code gets converted to:

var foo = React.createElement(Foo, null); // my custom component 1
var bar = React.createElement(Bar, null); // my custom component 2
React.createElement(MyComponent, { attachedComponents: [foo, bar] });

数组对象,typeof很奇怪。 typeof someArray 总是 returns "object":

console.log(typeof []);

测试数组的正确方法是使用Array.isArray:

console.log(Array.isArray([]));
console.log(Array.isArray({}));


I have seen this.props.children, but this does not seem reliable at all

嗯,它是可靠的,只是它并不总是 return 相同类型的值。有许多辅助函数可用于处理 this.props.children。看看 React.Children。例如。您可以使用 React.Children.toArray(this.props.children) 将值转换为真正的数组。

您在引用简单中突出显示的部分意味着您不应更改 this.props.children 本身的值。但这在任何方面都不是不合理的。