反应日选择器 DayPicker输入并在另一个组件中设置选定的日期



在一个组件中使用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>
)
}
}

控制台.log(选定日期(;记录选定的一天,但我如何访问 TodoForm 组件中的选定日子值并设置状态并呈现选定的日期?

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>
)
}

我也很难禁用今天之前的日期,但状态的事情是我最大的问题。谢谢!

将其作为道具传递

https://reactjs.org/docs/components-and-props.html

在 DayPickerComponent 中,您将选定的 Day 传递给 TodoForm:

<Todoform selectedDay={this.state.selectedDay} />

然后你需要在函数TodoForm上声明props:

function TodoForm(props) {
.....
....
.
console.log(props.selectedDay)
.
...
.....
}

因此,您可以在TodoForm中将选定的日期称为:

props.selectedDay

最新更新