2017-12-18 193 views
0

我需要创建一个const组件来呈现选项及其选项,但是由于代码返回的选项没有任何选项,因此无法呈现选项字段。问题在哪里?无法从const数组映射中渲染

谢谢你的建议。

import React from "react"; 

const FilterSelect = (props) => { 
    const {title, name, selectedValue, optionsValue, onChange} = {...props}; 

    const renderOptions = (optionsValue) => { 
     optionsValue.map((optionValue, i) => 
      <option value={optionValue.value} key={i}>{optionValue.name}</option> 
     ); 
    }; 

    return (
     <div className="filters-content-block"> 
      <h3 className="filters-subtitle">{title}</h3> 
      <select className="sl sl-fullwidth" onChange={onChange} required> 
       {renderOptions} 
      </select> 
     </div> 
    ); 
}; 

export default FilterSelect; 

回答

1

你的renderOptions是一个函数。您必须将其称为传递optionsValue作为参数;或者更改代码,以便renderOptions不再是功能,但一个数组,像这样:

const renderOptions = optionsValue.map((optionValue, i) => 
    <option value={optionValue.value} key={i}>{optionValue.name}</option> 
    ); 
+1

在我看来,这是最好的解决办法,所以我用它更改我的代码。谢谢! – Aitor

1

您定义renderOptions作为一种方法,但忘了发送optionsValue它。

<select className="sl sl-fullwidth" onChange={onChange} required> 
    {renderOptions(optionsValue)} 
</select> 
1

renderOptions是一个函数。所以,你必须调用它像这样:

<select className="sl sl-fullwidth" onChange={onChange} required> 
    {renderOptions()} 
</select> 

你可以摆脱optionsValue PARAM的,因为你的道具​​拥有它。你必须从函数返回。试着考虑一下:

const renderOptions =() => { 
     return optionsValue.map((optionValue, i) => 
      <option value={optionValue.value} key={i}>{optionValue.name}</option> 
     ); 
    };