我有新的反应,当我点击按钮时,我很难知道如何更改标题。非常感谢任何帮助。
import React, { Component } from 'react';
import './style.css';
class Layout extends Component {
constructor() {
super();
this.state = {
name:"Title",
};
}
func() {
this.setState({name: "NewTitle"});
}
render() {
// setTimeout(()=>{
// this.setState({name: "John"});
// },2000)
return (
<div className = "layout">
<h2>{this.state.name}</h2>
<p>{this.props.val}</p>
<input onClick = {this.func} type = "submit" value = "Done"/><br/>
</div>
);
}
}
答案 0 :(得分:2)
您缺少的主要部分是上下文this
。
因为this
具有函数范围,所以你正在调用的函数,即
onClick = {this.func}
失去了它的背景。
所以有两种方法可以达到这个目的。
1)使用胖箭头功能
胖箭头功能有词法范围。它将类的this
上下文传递给您声明的函数。
class Layout extends Component {
constructor() {
super();
this.state = {
name:"Title",
};
}
func = () => {
this.setState({name: "NewTitle"});
}
render() {
// setTimeout(()=>{
// this.setState({name: "John"});
// },2000)
return (
<div className = "layout">
<h2>{this.state.name}</h2>
<p>{this.props.val}</p>
<input onClick = {this.func} type = "submit" value = "Done"/><br/>
</div>
);
}
}
2)绑定上下文,即将this
上下文传递给您调用的函数
class Layout extends Component {
constructor() {
super();
this.func=this.func.bind(this)
this.state = {
name:"Title",
};
}
func(){
this.setState({name: "NewTitle"});
}
render() {
// setTimeout(()=>{
// this.setState({name: "John"});
// },2000)
return (
<div className = "layout">
<h2>{this.state.name}</h2>
<p>{this.props.val}</p>
<input onClick = {this.func} type = "submit" value = "Done"/><br/>
</div>
);
}
}
答案 1 :(得分:0)
注释代码以便更好地理解
import React, { Component } from 'react';
class Layout extends Component {
// missing props argument
constructor(props) {
super(props);
// better naming. tell the intent with the state name
this.state = {
title: "Default Title",
};
}
updateTitle = (e) => {
// it prevents the default behaviour of a form which is to submit
e.preventDefault();
// refs are probably outdated. task for you to improve it :)
const newTitle = this.refs['wordfield'].value;
this.setState({ title: newTitle });
this.refs['wordfield'].value = "";
}
render() {
return (
<div className="layout">
<h2>{this.state.title}</h2>
<form onSubmit={this.updateTitle}>
<p>Enter the new title</p>
<input type='text' ref='wordfield'/>
<button type='submit'>Start!</button>
</form>
</div>
);
}
}
export default Layout