我试图在呈现表单的各个部分时使用开关,但是,当我这样做时,我得到一个 e of undefined 的错误,当我 console.log inputType prop 时,我得到 3 undefined 和实际值。 我很想知道我做错了什么。
这是我尝试切换到的渲染
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Input from '../InputField';
import MultipleInput from '../multipleInput';
import ImageUploader from '../ImageUploader';
import './styles.scss';
const InputMultiple = ({currentState, handleMultpleChange, removeItem})=> (
<MultipleInput
value={currentState.services}
name="services"
handleMultpleChange={() => handleMultpleChange}
removeItem={removeItem}
/>
);
const InputImageUploader = ({ setTheState, currentState }) => (
<ImageUploader
setState={setTheState}
urls={currentState.urls}
files={currentState.files}
isDragging={currentState.isDragging}
/>
);
const InputTextArea = ({OnChange})=>(
<div className="accommodation_popup_innerContainer_inputContainer_div1">
<textarea
type="text"
name="description"
id="description"
className="input accommodation_popup_innerContainer_inputContainer_div1_inputs"
onChange={OnChange}
/>
</div>
);
const InputSingle = ({OnChange})=>(
<div className="accommodation_popup_innerContainer_inputContainer_div1">
<Input
type="text"
name={name}
id={labelName}
className="input accommodation_popup_innerContainer_inputContainer_div1_inputs"
onChange={OnChange}
/>
</div>
);
这是 switch 和它旁边传递的所有 props
const TypeOfInput = (inputType) => {
console.log(inputType);
switch (inputType) {
case 'InputMultiple': {
return InputMultiple;
}
case 'InputImageUploader': {
return InputImageUploader;
}
case 'InputTextArea': {
return InputTextArea;
}
default: {
return InputSingle;
}
}
};
const LabelInput = ({
labelName,
inputType,
name,
OnChange,
currentState,
setTheState,
handleMultpleChange,
removeItem,
}) => (
<div>
<div className="accommodation_popup_innerContainer_inputContainer_text">
<label className="accommodation_popup_innerContainer_inputContainer_text_texts">
{labelName}
</label>
</div>
{TypeOfInput(
inputType,
name,
OnChange,
currentState,
setTheState,
handleMultpleChange,
removeItem
)}
</div>
);
LabelInput.propTypes = {
labelName: PropTypes.string.isRequired,
onChange: PropTypes.func,
};
export default LabelInput;
我在哪里调用组件
<LabelInput
labelName="Services"
name="services"
inputType="InputMultiple"
OnChange={this.handleChange}
handleMultpleChange={() => this.handleMultpleChange}
removeItem={this.removeItem}
/>
最佳答案
handleMultpleChange={() => this.handleMultpleChange}
在你的 LabelInput
AND MultipleInput
组件中不正确。
您需要像这样调用该回调中的函数:() => this.handleMultpleChange()
或将函数设置为 this.handleMultpleChange
。我通常更喜欢后者,因为它更短。
那么这样做:
handleMultpleChange={() => this.handleMultpleChange()}
或者:
handleMultpleChange={this.handleMultpleChange}
*PS:拼写为multiple
,而不是multiple
关于javascript - 如何根据 Prop reactjs 渲染部分渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61172034/