【发布时间】:2016-08-26 14:49:07
【问题描述】:
刚开始学习 React.js 并且一直在使用 Lynda.com 来掌握事情的窍门。尽管视频系列如an earlier post 中提到的那样已经过时,但我已经能够在其他 Stack 帖子和 Google 的帮助下拼凑出这个项目。但是这个错误让我很难过。
我正试图向公告板应用程序添加新笔记。当我单击添加按钮(在屏幕右上角)时,它会引发 React Minified #31 错误,说我正在使用的对象作为 React 子对象无效。我认为这与我刚刚创建的按钮有关,但我不知道如何解决这个问题。
我正在使用 React 版本 15.3.1 和 Babel 版本 5.8.29(在教程中使用)。
Note.js
var Note = React.createClass({
getInitialState: function() {
return {editing: false}
},
edit: function() {
this.setState({editing: true});
},
save: function() {
// var val = ReactDOM.findDOMNode(this.refs.newText).value;
this.props.onChange(ReactDOM.findDOMNode(this.refs.newText).value,
this.props.index);
this.setState({editing: false});
},
remove: function() {
this.props.onRemove(this.props.index);
},
renderDisplay: function() {
return (
<div className="note">
<p>{this.props.children}</p>
<span>
<button onClick={this.edit}
className="btn btn-primary glyphicon glyphicon-pencil"/>
<button onClick={this.remove}
className="btn btn-danger glyphicon glyphicon-trash"/>
</span>
</div>
);
},
renderForm: function() {
return (
<div className="note">
<textarea ref="newText" defaultValue={this.props.children}
className="form-control"></textarea>
<button onClick={this.save} className="btn btn-success btn-sm glyphicon glyphicon-floppy-disk" />
</div>
)
},
render: function() {
if (this.state.editing) {
return this.renderForm();
}
else {
return this.renderDisplay();
}
}
});
var Board = React.createClass({
propTypes: {
count: function(props, propName) {
if (typeof props[propName] !== "number") {
return new Error ('The count property must be a number');
}
if (props[propName] > 100) {
return new Error ('Creating' + props[propName] + 'is silly');
}
}
},
getInitialState: function() {
return {
notes: []
};
},
add: function(text){
var array = this.state.notes;
array.push(text);
this.setState({notes:array});
},
update: function(newText, i) {
var array = this.state.notes;
array[i] = newText;
this.setState({notes:array});
},
remove: function(i) {
var array = this.state.notes;
array.splice(i, 1);
this.setState({note:array});
},
eachNote: function(note, i) {
return (
<Note key={i}
index={i}
onChange={this.update}
onRemove={this.remove}
>{note}</Note>
);
},
render: function() {
return <div className="board">
{this.state.notes.map(this.eachNote)}
<button className="btn btn-sm glyphicon glyphicon-plus"
onClick={this.add}></button>
</div>
}
});
ReactDOM.render(<Board count={10}/>,
document.getElementById('react-container'));
【问题讨论】:
标签: javascript reactjs