除了添加新笔记,一切似乎都可以在这个小应用程序中使用。按钮位于Board组件上。
我知道这个问题通常是由于未正确绑定“ this”的值引起的。我不确定这是否是这里的问题,或者我是否缺少其他东西。谢谢
演示:http://jsbin.com/pewahi/edit?js,输出
/* jshint asi:true */ class Note extends React.Component { constructor(props) { super(props) this.state = { editing: props.editing } } render() { if (this.state.editing) { return this.renderForm() } else { return this.renderDisplay() } } edit() { this.setState({editing: true}) } save() { this.props.changeHandler(this.refs.newText.getDOMNode().value, this.props.index) this.setState({editing: false}) } remove() { this.props.removeHandler(this.props.index) } renderDisplay() { return ( <div className="note"> <p>{this.props.children}</p> <span> <button className="btn btn-sm glyphicon glyphicon-pencil" onClick={this.edit.bind(this)}></button> <button className="btn btn-sm glyphicon glyphicon-trash" onClick={this.remove.bind(this)}></button> </span> </div> ) } renderForm() { return ( <div className="note"> <textarea ref="newText" defaultValue={this.props.children} className="form-control"></textarea> <button onClick={this.save.bind(this)} className="btn btn-success btn-sm"><span className="glyphicon glyphicon-floppy-disk"></span> Save</button> </div> ) } } Note.propTypes = { editing: React.PropTypes.bool, onChange: React.PropTypes.func, onRemove: React.PropTypes.func } Note.defaultProps = { editing: false } class Board extends React.Component { constructor(props) { super(props) this.state = { notes: [{note: 'hi', id: this.nextId()}] } } update(newText, i) { var arr = this.state.notes arr[i].note = newText this.setState({notes: arr}) } remove(i) { var arr = this.state.notes arr.splice(i, 1) this.setState({notes: arr}) } addNote(text) { var arr = this.state.notes arr.push({ id: this.nextId(), note: text }) console.log(arr) this.setState({notes: arr}) } nextId() { this.uniqueId = this.uniqueId || 0 return ++this.uniqueId } eachNote(note, i) { return ( <Note key={note.id} index={i} changeHandler={this.update.bind(this)} removeHandler={this.remove.bind(this)} >{note.note} </Note> ) } render() { return ( <div className="board"> {this.state.notes.map(this.eachNote, this)} <button onClick={this.addNote.bind(this, "new note")} className="btn btn-success btn-sm glyphicon glyphicon-plus"></button> </div> ) } } React.render( <Board />, document.getElementById('message-board') )
您的代码很好。这可能是JSBin的错误,以及如何使用Babel处理转译。如果将杂项添加// noprotect到代码的顶部,您将看到它起作用。
// noprotect