有条件地指定组件的道具

问题描述 投票:0回答:1

如果{type} ==='dateTime',我想在下面的ReactDatePicker组件中包含showTimeSelect属性,否则我想忽略它,但是它目前不起作用。我是React的菜鸟,因此希望您能指导它工作。

这样做的目的是因为我以一种形式使用ReactDatePicker,有时我希望它显示为日期选择器,而其他时候我希望它显示为时间选择器。方法是在ReactDatePicker组件中添加一个属性,即showTimeSelect。

import React from 'react';
import ReactDatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import { Controller } from 'react-hook-form';
function FormDate({ name, question, register, control, type }) {

  const varShowTimeSelect = ({ type }) =>
    ({ type } === 'dateTime' ? { showTimeSelect } : {});

  return (
    <div className="form-group">
      <label htmlFor={name}>{question}</label>
      <div className="input-group date col-xs-5">
        <Controller
          as={
            <ReactDatePicker
              dateFormat="dd/MM/yyyy"
              placeholderText="Select date"
              {varShowTimeSelect} //Conditionally show showTimeSelect prop
            />
          }
          control={control}
          name={name}
          ref={register}
          id={name}
          valueName="selected"
          onChange={([selected]) => selected}
        />
      </div>
    </div>
  );
}
export default FormDate;

非常感谢,

Katie

reactjs functional-programming components react-props react-datetime
1个回答
0
投票

在属性值内添加条件:

<ReactDatePicker
  dateFormat="dd/MM/yyyy"
  placeholderText="Select date"
  showTimeSelect={type === 'dateTime'}
/>

function FormDate({ name, question, register, control, type }) {
  return (
    <div className="form-group">
      <label htmlFor={name}>{question}</label>
      <div className="input-group date col-xs-5">
        <Controller
          as={
            <ReactDatePicker
              dateFormat="dd/MM/yyyy"
              placeholderText="Select date"
              showTimeSelect={type === 'dateTime'}
            />
          }
          control={control}
          name={name}
          ref={register}
          id={name}
          valueName="selected"
          onChange={([selected]) => selected}
        />
      </div>
    </div>
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.