为何setState无法将state中的editing字段改为true?
解决React组件中edit函数无法设置editing状态的问题
嘿,我看到你的Note组件里edit函数出问题了,咱们一步步拆解解决哈!
首先看最明显的错误:setState调用方式错了
你写的this.setState = ({ editing: true })是把setState当成变量赋值了,但实际上this.setState是React组件提供的方法,正确姿势是把状态对象作为参数传进去,不是赋值:
edit() { this.setState({ editing: true }); }
然后是容易忽略的this绑定问题
在React类组件里,类定义的方法(比如你的edit、remove)默认不会自动绑定组件实例的this,直接在模板里用onClick={this.edit}的话,触发时this会变成undefined,自然没法调用setState。这里给你三种常用的解决方式:
方式一:在constructor里手动绑定
constructor (props) { super(props); this.state = { editing: false }; // 把方法的this绑定到组件实例上 this.edit = this.edit.bind(this); this.remove = this.remove.bind(this); this.save = this.save.bind(this); }
方式二:用箭头函数定义类方法
箭头函数会自动捕获当前上下文的this,写起来更简洁:
edit = () => { this.setState({ editing: true }); }; remove = () => { alert("removed"); }; save = () => { alert("saved"); };
方式三:调用时用箭头函数包裹
在render的点击事件里直接用箭头函数包裹方法调用:
<button onClick={() => this.edit()}>编辑</button>
最后补全完整的组件代码
你提供的代码里renderDisplay和render方法都没写完,这里给你补全可运行的完整版本:
class Note extends React.Component { constructor(props) { super(props); this.state = { editing: false }; // 这里用方式一绑定this,你也可以换成箭头函数写法 this.edit = this.edit.bind(this); this.remove = this.remove.bind(this); this.save = this.save.bind(this); } edit() { this.setState({ editing: true }); } remove() { alert("removed"); } save() { alert("saved"); // 保存后记得把编辑状态切回去 this.setState({ editing: false }); } renderForm() { return ( <div className="note"> <form onSubmit={(e) => e.preventDefault()}> {/* 阻止表单默认跳转 */} <textarea defaultValue={this.props.content} /> {/* 可以传入初始笔记内容 */} <button onClick={this.save}>保存</button> <button onClick={this.remove}>删除</button> </form> </div> ); } renderDisplay() { return ( <div className="note"> <p>{this.props.content}</p> <button onClick={this.edit}>编辑</button> <button onClick={this.remove}>删除</button> </div> ); } render() { // 根据editing状态切换显示内容 return this.state.editing ? this.renderForm() : this.renderDisplay(); } }
这样修改后,点击「编辑」按钮就能正确把editing状态改成true,切换到表单模式啦!
内容的提问来源于stack exchange,提问作者Eyal S
相关产品推荐
相关产品推荐

