首页 > 解决方案 > React semantic-ui-date-picker 默认日期不起作用

问题描述

这是我的代码:

import SemanticDatepicker from 'react-semantic-ui-datepickers'
class InsightsTable extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      initial_value: '2012-10-20',
    }
  }

  render() {
    const { initial_value } = this.state
    return (
      <SemanticDatepicker
        selected={(initial_value, 'DD-MM-YYYY')}
        onChange={this.handleFromDate}
      />
    )
  }
}

在这里,我使用 react-semantic-ui-datepickers 进行日期选择功能。Butm 在我的情况下,我想默认保留一个数据,默认日期来自 api,所以我将初始日期存储在状态中并在 datepicker 中使用。

但是,它不起作用。我检查了其他一些问题仍然没有解决。请看一看

标签: reactjsdatepickersemantic-ui

解决方案


这是我的解决方案,希望对您有所帮助!诀窍是将日期对象传递给value道具。在我的例子中,SemanticDatepicker 被包装到另一个组件中,该组件从 API 获取默认日期作为初始(默认)预选日期。

export class DateInput extends Component {
    constructor(props) {
        super(props);

        const d = new Date(this.props.date);
        const initialDateValue = d;
      
        this.state = {
            defaultDateValue: initialDateValue,
        };
    }
    
    handleChange = (e, data) => {
        if (data.value) {
            const newDateValue = new Date(data.value);
            return this.setState({ defaultDateValue: newDateValue });
        } else {
            return data.value;
        }
    };
    
    render() {
        return (
            <SemanticDatepicker
                label="Date"
                id="transactionDate"
                format="DD/MM/YYYY"
                required={this.props.required}
                onChange={this.handleChange.bind(this)}
                showToday={true}
                value={this.state.defaultDateValue}
            />
        );
    }
}

推荐阅读