在提交表单时阻止日期刷新



我希望在提交表单时,下面显示的日期在下一次提交时不会刷新。

目前,如果我输入分钟或秒,只要我在文本区输入一个字母或添加一个新笔记,所有笔记的'{new Date(). tolocaledatestring()}'都会刷新。我想要阻塞进程

class AddNote extends React.Component {


render() {
return (
<React.Fragment>
<h3 className="NoteDetails">
{new Date().toLocaleDateString()}</h3>
<span className="NoteLine"></span>
<div className="notes">
<p>{this.props.isTextDisplayed && this.props.text}</p>
</div>
<button
type="reset"
className="deleteBtn"
onClick={() => this.props.handleDeleteNote(this.props.noteIndex)}
>
Supprimer
</button>
</React.Fragment>
);
}
}
export default AddNote;

class Note extends React.Component {
constructor(props) {
super(props);
this.state = { value: "", isTextDisplayed: false, notes: [] };

this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleDeleteNote = this.handleDeleteNote.bind(this);
}

handleChange(event) {
this.setState({ value: event.target.value });
}

handleSubmit(event) {
event.preventDefault();
this.setState({ isTextDisplayed: true });
this.setState(
{ notes: [ this.state.value,...this.state.notes,]},
this.setState({ value: "" })

);
}

handleDeleteNote(index) {
this.setState({
notes: this.state.notes.filter((_, itemIndex) => index !== itemIndex)
});
}

render() {
return (
<React.Fragment>
<div className="title">
<h1>Notes</h1>
<span className="LineTitle"></span>
</div>


<form id="form" onSubmit={this.handleSubmit}>
<textarea
className="textNote"
id="textZone"
value={this.state.value}
onChange={this.handleChange}
required
></textarea>
<button type="submit" className="addBtn">
Ajouter
</button>
</form>

{this.state.notes.map((note, noteIndex) => (
<AddNote
key={noteIndex}
text={note}
isTextDisplayed={this.state.isTextDisplayed}
noteIndex={noteIndex}
handleDeleteNote={this.handleDeleteNote}
/>
))}
</React.Fragment>
);
}
}

export default Note;

在React中,当你使用之前的值更新状态值时,使用callback参数。这是由于React更新的异步特性。(见https://reactjs.org/docs/state-and-lifecycle.html state-updates-may-be-asynchronous)

handleDeleteNote

handleDeleteNote=(index)=>{ // arrow prevents the need to bind
this.setState((state)=>({
notes: state.notes.filter((_, itemIndex) => index !== itemIndex)
}));
}

handleSubmit

handleSubmit=(event)=>{ // arrow prevents the need to bind
event.preventDefault();
this.setState((state)=>({
isTextDisplayed: true,
notes: [state.value].concat(state.notes)
value: ''
}));
}

如果您希望<h3 className="NoteDetails">中的日期保持固定,然后,而不是每次重新渲染{new Date().toLocaleDateString(),设置为一个状态属性。

this.state = {currentDate: new Date().toLocaleDateString()};
<h3 className="NoteDetails">{this.state.currentDate}</h3>

相关内容

  • 没有找到相关文章

最新更新