如果{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;
非常感谢,
凯蒂
答案 0 :(得分:2)
在showTimeSelect
接受boolean
类型的情况下,在属性值中添加条件:
<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>
);
}
答案 1 :(得分:1)
除了丹尼斯提出的建议(在这种情况下,我认为这是更好的解决方案),如果您想完全不通过道具 ,则可以使用{{ 3}}:
function FormDate({ name, question, register, control, type }) {
const showTimeSelectProps = type === 'dateTime' ? { showTimeSelect: true } : {};
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"
{...showTimeSelectProps} //Conditionally show showTimeSelect prop
/>
}
control={control}
name={name}
ref={register}
id={name}
valueName="selected"
onChange={([selected]) => selected}
/>
</div>
</div>
);
}