通过变量将道具传递到组件

游击电台

我有一个类组件,它呈现输入和工具提示并控制状态。<SelectInputType>组件的工作是采取“类型”的单个支柱并呈现一个文本输入,一个textarea,选择输入或一个复选框组组件。需要通过此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传播属性将道具向下传递给SelectInputType组件,但是我不知道如何将它们传递给4个输入组件(如果我将它们传递给我,某些道具会出现错误,但不会)在特定组件上有效吗?)

tenor528

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章