即使我可以访问其属性,参数对象的长度也为零

时间:2019-12-17 03:02:32

标签: javascript reactjs typescript

当我将参数传递给函数,甚至可以访问其属性时,为什么arguments对象的长度为零? 我说的是所有javascript函数都实现的arguments对象,您可以从中访问函数arguments。您可以在这里了解更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments

发生的事情是,当我在控制台上打印arguments对象的长度时,它说它具有cero长度,但是当我从函数(组件)内部访问它时,我仍然可以使用其属性之一。您可以阅读下面的代码中的注释以获取更多详细信息。

我正在使用打字稿进行反应。

interface Props{
id: string;
className?: string;    
}

export const Buttons: React.FC<Props> = function(){


  function arg(){

    console.log("Funciona");
    console.log("arguments object: "+arguments);
    {/*This prints to the console that the arguments objects is of cero (0) length*/}
    {/*Even when is posible to access
    the id property that I have passed from App component*/}
    console.log("arguments object: "+arguments.length);
    console.log("arguments object: "+arguments[0]);

    for(let i=0; i < arguments.length; i++){

      {/*It will never enter the for loop*/}

      console.log("arguments object: "+arguments[i]);

    }

  }{/*end arg*/}

  React.useEffect(

    ()=>{

      window.setTimeout(arg, 5000);

    },
    []

  );

  return(

    {/*This will work as I'm  able to see the id from the dev tools*/}
    <section id={arguments[0].id}>{}

      <div className="container">

        <p>Hello World</p>

      </div>

    </section>

  );
} 

在这里我通过了id属性:

const App: React.FC = () => {
  return (

    <div className="App">

      <Buttons id="buttons" />

    </div>

  );
}

1 个答案:

答案 0 :(得分:1)

我不确定您的问题吗?

您是否要通过执行 arguments [0] .id 来访问 id道具

您可以通过以下方式访问组件的“参数”(称为react中的props):

替换:

export const Buttons: React.FC<Props> = function(){

通过:

export const Buttons: React.FC<Props> = function(props){

然后打电话

props.id

祝你好运