在地图功能中传递道具无效。将其作为主要工作

时间:2019-08-25 01:36:12

标签: javascript arrays reactjs array-map

我正在将一个数组作为道具从App.js传递到组件B。该数组:

myOptions: [
{
    id: 1,
    option: "Option1"
},
{
    id: 2,
    option: "Option2"
},
{
    id: 3,
    option: "Option3"
}
]

从App.js中,我将其传递给组件B:

<ComponentB 
    options={this.state.myOptions}
/>    

ComponentB:

import React from 'react';

import ComponentC from './ComponentC';


function ComponentB (props) {

  function renderOptions(key) {
    return(
      <ComponentC
        key={key.option}
        optionContent={key.option} //this is my question
        answers={props.option}
      />
    );
}

    return (
        <div>
        <h3> ComponentB </h3>
        {props.options.map(renderOptions)}
      </div>
    );

}

export default ComponentB;

ComponentC仅显示optionContent:

import React from 'react';

function ComponentC(props) {
  return (
    <div>
        {props.optionContent}
    </div>
  );
}

export default ComponentC;

尽管代码可以正常工作,但是我不确定为什么在renderOptions函数中,我需要使用key.option来传递optionContent={key.option}道具。当我使用props.option时,它不起作用。

是因为renderOptions函数嵌套在ComponentB函数中吗?

1 个答案:

答案 0 :(得分:4)

首先,您应该了解map()的工作原理。

在您的代码中,

function ComponentB (props) {
  function renderOptions(key) {
    return(
      <ComponentC
        key={key.option}
        optionContent={key.option} //this is my question
        answers={props.option}
      />
    );
  }
  return (
      <div>
      <h3> ComponentB </h3>
      {props.options.map(renderOptions)}
    </div>
  );
}

您可以像这样map()使用{props.options.map(renderOptions)},它看起来还可以。

但是您应该对map()的论点有所了解。

您可以阅读

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/map

通常,map()具有3个参数,并且将其中2个用作参数。 currentValueindex

,然后再次返回您的代码。

您自己传递了函数renderOptions()

这意味着renderOptions()可以从map()获取所有参数

您可以触摸currentValueindex和其他东西。

但是,renderOptions()只有一个参数key

(如果您想触摸所有自变量,则应这样写function renderOptions(v, i, arr)

因此,您只能触摸keycurrentValue

currentValue具有数组的每个项目。

{
    id: 1,
    option: "Option1"
}

您必须这样重写代码。

function renderOptions(v,i,arr) {
    return(
      <ComponentC
        key={v.id} // because the key should be unique.
        optionContent={v.option} 
        answers={arr} // Actually, I don't understand this purpose.
      />
    );
}