【发布时间】:2019-10-11 12:10:55
【问题描述】:
import React from "react";
import PropTypes from "prop-types";
const Component = ({ children }) => <div>{children}</div>;
Component.propTypes = { children: PropTypes.object }; //what is not clear
它有效。但为什么它会起作用?由于我正在使用 JavaScript,因此我以前从未遇到过这种情况。出于好奇,我试过这个:
const fn = () => {};
fn.prop = true;
console.log(fn, fn(), "it seems like prop is not assigned");
//just to clarify for those who don't understand the question:
const obj = {};
obj.prop = true;
console.log(obj, "prop assigned to the object. fine.");
const secondFn = () => ({});
const objFromSecondFn = secondFn();
objFromSecondFn.prop = true;
console.log(objFromSecondFn, "prop assigned to the object. clear.");
console.log("comparison:", fn, obj, objFromSecondFn);
但它似乎没有做任何事情。那么这种方法可以解决什么问题,以及背后发生了什么?
【问题讨论】:
-
你认为它应该怎么做?
-
你的问题不清楚。特别是你的第二个例子。
-
函数是对象,因此您可以像使用对象一样向它们添加属性
-
(这两个代码sn-ps有什么关系?)
-
"好像没有分配 props" - 是的,但它被分配给
fn而不是fn()。并且根据您的控制台实现,它在记录函数时仅显示函数代码,而不是其属性。但是当您使用console.log(fn.prop, "the property itself")时,它就会出现。
标签: javascript