我有一个类组件,它呈现输入和工具提示并控制状态。 <SelectInputType>
组件作业是采用“类型”的单个支柱,并呈现文本输入,文本区域,选择输入或复选框组件。需要通过此SelectInputType组件传递大量的道具,其中一些与所有4个输入组件(placeholderText和例如所需)相关,其中一些特定于特定输入(例如选项是仅与复选框和选择输入相关。)
render() {
const inputProps = {};
inputProps.placeholderText = this.props.placeholderText;
inputProps.required = this.props.required;
inputProps.class = this.props.class;
inputProps.value = this.props.value;
inputProps.options = this.props.options;
inputProps.updateText = this.handleInput;
inputProps.handleFocus = this.focusIn;
inputProps.handleBlur = this.focusOut;
inputProps.handleCheckboxChange = e => this.addCheckboxToList(e);
inputProps.closeCheckboxSelector = this.closeCheckboxSelector;
inputProps.readableSelectedCheckboxes = this.state.readableSelectedCheckboxes;
const inputClass = classNames('input-with-tooltip', {
focus: this.state.focus,
'step-complete': this.state.completed,
});
return (
<div className={inputClass}>
<InputTooltip
tooltipText={this.props.tooltipText}
completed={this.state.completed}
/>
<div className="drill-creation-input">
<SelectInputType type={this.props.type} {...inputProps} />
</div>
</div>
);
}
我的SelectInputType组件看起来像这样......
const SelectInputType = (props) => {
let component;
if (props.type === 'title') {
component = <TextInput />;
} else if (props.type === 'text') {
component = <TextareaInput />;
} else if (props.type === 'checkbox') {
component = <CheckboxInput />;
} else if (props.type === 'select') {
component = <SelectInput />;
}
return (
<div>
{component}
// Need to pass props through to this?
</div>
);
};
我正在使用JSX spread属性将props传递给SelectInputType组件,但我不知道如何将这些传递给4个输入组件(如果我确实传递它们将会出现错误某些道具对特定组件无效?)
答案 0 :(得分:2)
您也可以将组件类型保存在变量中,而不是组件本身:
const SelectInputType = (props) => {
let ComponentType;
if (props.type === 'title') {
ComponentType = TextInput;
} else if (props.type === 'text') {
ComponentType = TextareaInput;
} else if (props.type === 'checkbox') {
ComponentType = CheckboxInput;
} else if (props.type === 'select') {
ComponentType = SelectInput;
}
return (
<div>
<ComponentType {..props} />
</div>
);
};
答案 1 :(得分:1)
您可能会收到错误。如果是这样,您可以创建实用程序函数来提取每个输入类型所需的道具:
extractTextInputProps(props) {
const { value, className, required } = props
return { value, className, required }
}
extractSelectInputProps(props) {
const { value, handleBlur, updateText } = props
return { value, handleBlur, updateText }
}
您可以从中提取更通用的功能,这样您就不必重复两次属性名称。
然后在使用spread运算符创建组件时使用它们:
let component;
if (props.type === 'title') {
component = <TextInput { ...extractTextInputProps(props) } />;
} else if (props.type === 'text') {
component = <TextareaInput />;
} else if (props.type === 'checkbox') {
component = <CheckboxInput />;
} else if (props.type === 'select') {
component = <SelectInput { ...extractSelectInputProps(props) } />;
}