【发布时间】:2019-11-16 23:25:33
【问题描述】:
我正在尝试在 React 中创建一个笔记应用程序。 当使用输入框中的值按下“添加注释”按钮时,应用程序应添加新注释。
不幸的是,当我尝试将注释推送到列表并更新父母状态时,更改并未反映在屏幕上或反应调试器中。
将新笔记推送到列表中可以在警报行中看到,但在其他任何地方都看不到。
这里是包含原始笔记状态的父组件:
class NoteApplication extends React.Component {
constructor(props) {
super(props);
this.state = {
notes: Array(),
};
this.update = this.update.bind(this);
this.state.notes.push("Sample note");
}
update(notes) {
return () => {
this.setState({
notes: notes
});
}
}
render() {
return (
<div>
<h1>React Notes</h1>
<div class="InsertBarDiv">
<InsertBar
notes={this.state.notes}
update = {this.update}
/>
</div>
<div class="NotesDiv">
<Notes
notes={this.state.notes}
/>
</div>
</div>
)
}
}
这是子组件
class InsertBar extends React.Component {
constructor(props) {
super(props);
this.state = {value:''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
const notes = this.props.notes.slice();
notes.push(this.state.value);
this.props.update(notes);
alert(notes);
event.preventDefault();
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<input class="noteInsertBar" type="text" name="" onChange={this.handleChange}/>
<input class="insertBut" type="submit" value="Add Note"/>
</form>
</div>
)
}
}
class Notes extends React.Component {
renderNote(i) {
return (
<div>
{this.props.notes}
</div>
)
}
render() {
return (
<div>
<h2>Notes:</h2>
<div class="FullNote">
{this.renderNote(1)}
</div>
</div>
)
}
}
我希望将笔记推送到笔记列表的副本,并将父母状态设置为笔记列表的新副本。
然后我希望它会显示在屏幕上。
【问题讨论】:
-
您是否希望显示一系列笔记?
标签: javascript reactjs