这是我的react功能组件
,我将输入作为要显示的props
发送,然后循环遍历输入以检查要根据哪些输入显示条件。这是我的组件:-
const TopInputComponent = (props) => {
const inputs = props.inputs;
inputs.map((input,index)=>{
if(input.type == "textInput"){
return (<Textfield key={index}
onKeyDown={(event)=>{
if(event.key == "Enter"){
onFilterSelected({'min_price':parseInt(event.target.value)});
}
}}
label={input.placeholder}
floatingLabel
/> )
}else if(input.type == "selectInput"){
return (<div key={index}>
<label>{input.placeholder}</label>
<select >
<option value="1">1</option>
<option value="2">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>)
}
})
}
我收到此错误:
"A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object."
最佳答案
有两个、三个、可能四个问题:
您没有从函数中返回任何内容,因为您还没有
map
返回结果。React 组件必须返回单个元素或
null
,它不能返回数组。在
map
回调中,仅当input.type
为"textInput"
或时才返回某些内容“selectInput”
,如果是其他东西则不然。这将在结果数组中留下未定义
值。如果这是仅有两个可能的值,请将else if(input.type == "selectInput"){
更改为} else {
。如果不是,则处理其他情况。Textfield
的开始标记中的floatingLabel
看起来很奇怪,它将是一个独立的 bool 属性。
因此,您可能希望将这些元素包装在某些东西中,例如 div
(请参阅 ***
行):
const TopInputComponent = (props) => {
const inputs = props.inputs;
return <div>{inputs.map((input,index)=>{ // ***
if(input.type == "textInput"){
return (<Textfield key={index}
onKeyDown={(event)=>{
if(event.key == "Enter"){
onFilterSelected({'min_price':parseInt(event.target.value)});
}
}}
label={input.placeholder}
floatingLabel
/> )
} else { // *** Removed: if(input.type == "selectInput"){
return (<div key={index}>
<label>{input.placeholder}</label>
<select >
<option value="1">1</option>
<option value="2">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>)
}
})}</div>; // ***
}
简化的实例:
const MyComponent = props => {
const {inputs} = props;
return <div>
{inputs.map((input, index) => <input key={index} type={input.type} name={input.name} value={input.value || ''} />)}
</div>;
};
ReactDOM.render(
<MyComponent inputs={[
{type: "text", name: "one"},
{type: "button", name: "btn", value: "Click me"}
]} />,
document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
关于javascript - 为什么我的 React 组件没有渲染?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43423852/