我正在演示应用程序中使用此日期选择器
https://www.npmjs.com/package/react-datepicker 但是当我单击输入字段时,日期选择器打开。当用户单击右侧的按钮和图标而不是输入单击时,我们可以打开日期选择器吗?
import React from "react";
import ReactDOM from "react-dom";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import "./styles.css";
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
startDate: new Date()
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(date) {
this.setState({
startDate: date
});
}
openDatePicker = () => {};
render() {
return (
<div>
<DatePicker
selected={this.state.startDate}
onChange={this.handleChange}
/>
<button onClick={this.openDatePicker}>openDate</button>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Example />, rootElement);
答案 0 :(得分:0)
是的,除了单击组件本身之外,还可以将其打开。您可以使用Datepicker的open
属性进行控制。这是您代码的修改版本:
import React from "react";
import ReactDOM from "react-dom";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import "./styles.css";
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
startDate: new Date(),
datePickerIsOpen: false,
};
this.handleChange = this.handleChange.bind(this);
this.openDatePicker = this.openDatePicker.bind(this)
}
handleChange(date) {
this.setState({
startDate: date
});
}
openDatePicker() {
this.setState({
datePickerIsOpen: !this.state.datePickerIsOpen,
});
};
render() {
return (
<div>
<button onClick={this.openDatePicker}>openDate</button>
<DatePicker
selected={this.state.startDate}
onChange={this.handleChange}
onClickOutside={this.openDatePicker}
open={this.state.datePickerIsOpen}
/>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Example />, rootElement);
如您所见,我们已经向Example类添加了一个状态,该状态控制Datepicker的open
属性。我还添加了onClickOutside,可用来确定如果用户在日期选择器打开后单击外部,将会发生什么情况。
答案 1 :(得分:0)
您需要将按钮设置为customInput
import React from 'react'
const CustomInput = React.forwardRef((props,ref) => {
return (
<button onClick={props.onClick} ref={ref}>
{props.value || props.placeholder}
</button>
)
})
export default CustomInput;
然后在主要组件中。做这个
import React from "react";
import ReactDOM from "react-dom";
import DatePicker from "react-datepicker";
import CustomInput from "./CustomInput"
import "react-datepicker/dist/react-datepicker.css";
import "./styles.css";
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
startDate: new Date()
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(date) {
this.setState({
startDate: date
});
}
render() {
return (
<div>
<DatePicker
selected={this.state.startDate}
onChange={this.handleChange}
customInput={<CustomInput />}
placeholderText="openDate"
/>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Example />, rootElement);