在一个组件中使用 DayPicker,我想将选定的日期导入 TodoForm 组件,并使用该值设置状态,以便在每个待办事项中保存和呈现选定的日期。
class DayPickerComponent extends Component {
constructor(props) {
super(props);
this.handleDayChange = this.handleDayChange.bind(this);
this.state = {
selectedDay: undefined,
isEmpty: true,
isDisabled: false
}
}
handleDayChange(selectedDay, modifiers, dayPickerInput) {
const input = dayPickerInput.getInput();
this.setState({
selectedDay,
isEmpty: !input.value.trim(),
isDisabled: modifiers.disabled === true
})
}
render() {
const today = new Date();
const { selectedDay, isDisabled, isEmpty } = this.state;
console.log('selectedDay: ', selectedDay)
return (
<span>
<DayPickerInput
disabledDays={{
before: today
}}
onDayChange={this.handleDayChange}
/>
</span>
)
}
}
console.log(selectedDay); 记录 selectedDay 但如何访问 TodoForm 组件中的 selectedDay 值并设置状态并呈现所选日期?
function TodoForm({addTodo}) {
const initialState = {
title: '',
due_date: '',
description: '',
completed: false
}
const [state, setState] = useState(initialState);
const handleSubmit = e => {
e.preventDefault();
// if (state.title && state.due_date && state.description) {
addTodo(state.title, state.due_date, state.description)
// } else {
// alert('A task must contain a title, description, and a due date. Please add the required information and then submit.')
// }
resetInput();
}
function handleChange(e) {
const value = e.target.value;
setState({
...state,
[e.target.name]: value,
})
}
function resetInput () {
setState(initialState);
}
return (
<form id='form' onSubmit={handleSubmit}>
<div>
<span className='title'>Title: </span>
<input type='text' className='input' name='title' value={state.title} onChange={handleChange} />
</div>
<div>
<span className='title'> Due Date: </span>
{/* <input type='text' className='input' name='due_date' value={state.due_date} onChange={handleChange} /> */}
<DayPickerComponent selectedDay />
</div>
<div>
<span className='title'>Description: </span>
<input type='text' className='input' name='description' value={state.description} onChange={handleChange} />
<span id='add-button' className='add-button-wrapper'>
<button id='add-button-appearance'>
+
</button>
<span className='add-button-tooltiptext'>add</span>
</span>
</div>
</form>
)
}
我也很难禁用今天之前的日期,但状态是我最大的问题。谢谢!