需要更简化此代码。我想做的就是让onClick事件执行一个操作,但是对于我想做的事情,代码似乎太复杂了:
import React, { Component } from 'react';
class Comment extends Component{
constructor(){
super();
this.state= {name:''};
this.display = this.display.bind(this);
}
display(){
this.setState({name:'Test2'});
}
render(){
return(
<div>
<button onClick={this.display}>Click me</button>
<h1>{this.state.name}</h1>
</div>
)
}
}
export default Comment;
答案 0 :(得分:3)
如果您使用的是React 16.8,则可以将基于useState
hook的功能部件作为一个更简单的实现,如下所示:
import React, { useState } from 'react';
/* Define functional equivalent of Comment component */
const Comment = () => {
/* Setup name state getter/setter via useState hook */
const [name, setName] = useState('')
/* Render comment JSX */
return (<div>
<button onClick={() => setName('Test2')}>Click me</button>
<h1>{name}</h1>
</div>)
}
export default Comment;
答案 1 :(得分:0)
如果您不想尝试Hooks
(在V16.8中添加了挂钩),那么arrow function也是一个简单的选择,
class Comment extends Component {
constructor() {
super()
this.state = {name: ''}
}
render() {
return (
<div>
<button onClick={() => this.setState({name: 'Test2'})}>Click me</button>
<h1>{this.state.name}</h1>
</div>
)
}
}