如何在React中的组件上设置条件属性

时间:2019-02-12 15:57:55

标签: reactjs

我正在使用React Date选择器插件,称为react-flatpickr。当我希望禁用Flatpickr时,我需要在Flatpickr组件上设置一个名为“ disabled”的道具。 disable不是可以设置为true或false的布尔值。禁用是没有值的属性。是否只有在readOnly为true时才使用禁用的prop初始化Flatpickr组件的方法,而不是此可怕的重复代码?

getFlatPickr(id, ref, defaultDate, minDate, readOnly){
    if (readOnly) {
        return (
            <Flatpickr
                id={id}
                name={id}
                disabled
                className={"form-control"}
                placeholder={"MM/DD/YYYY HH:MM AM/PM"}
                options={{
                    enableTime: true,
                    dateFormat: this.state.flatpickrDateFormat,
                }}
            />
        );
    } else {
        return (
            <Flatpickr
                id={id}
                name={id}
                className={"form-control"}
                placeholder={"MM/DD/YYYY HH:MM AM/PM"}
                options={{
                    enableTime: true,
                    dateFormat: this.state.flatpickrDateFormat
                }}
            />
        );
    }
}

1 个答案:

答案 0 :(得分:2)

当然,只需将disabled属性直接设置为您的readOnly变量:

getFlatPickr(id, ref, defaultDate, minDate, readOnly) {
        return (
            <Flatpickr
                id={id}
                name={id}
                disabled={readOnly}
                className={"form-control"}
                placeholder={"MM/DD/YYYY HH:MM AM/PM"}
                options={{
                    enableTime: true,
                    dateFormat: this.state.flatpickrDateFormat
                }}
            />
        );
    }
}

语法更短:

getFlatPickr = (id, ref, defaultDate, minDate, readOnly) => (
    <Flatpickr
        id={id}
        name={id}
        disabled={readOnly}
        className="form-control"
        placeholder="MM/DD/YYYY HH:MM AM/PM"
        options={{
            enableTime: true,
            dateFormat: this.state.flatpickrDateFormat
        }}
    />
)