gpt4 book ai didi

javascript - 通过变量将 props 传递给组件

转载 作者:行者123 更新时间:2023-11-29 19:03:02 25 4
gpt4 key购买 nike

我有一个类组件,它呈现输入和工具提示并控制状态。 <SelectInputType> components 的工作是采用“type”的单个 prop 并呈现文本输入、文本区域、选择输入或复选框组组件。有大量 Prop 需要通过此 SelectInputType 组件传递,其中一些与所有 4 个输入组件相关(例如 placeholderText 和 required),其中一些特定于特定输入(例如选项是仅与复选框和选择输入相关)。

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 个输入组件(如果我传递它们,我会不会出错某些 Prop 在特定组件上无效?)

最佳答案

您也可以将组件类型保存在变量中,而不是组件本身:

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>
);
};

关于javascript - 通过变量将 props 传递给组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45417427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com