React组件:
import React from 'react';
class Board extends React.Component {
constructor() {
super();
this.state = {
comments: [
{
auhor:"阿大",
time:new Date().getTime(),
comment:"good people"
}
]
}
//修正事件指针
this.addComment=this.addComment.bind(this);
}
addComment(){
console.log(this.refs)
console.log(this.render())
//添加信息,set数据,实时渲染
var comment={
auhor:this.refs.author.value,
time:new Date().getTime(),
comment:this.refs.comment2.value
}
this.state.comments.push(comment);
this.setState({
comments:this.state.comments
});
}
render() {
//遍历结果
let info =this.state.comments.map((item, index) => {
return <div key={index}>
<span>{item.auhor}</span><br/>
<span>{item.time}</span><br/>
<span>{item.comment}</span>
</div>
})
return (
<div>
<h2>留言板</h2>
<div className="comments">
{info}
</div>
<input type="text" ref="author"/><br/>
<textarea ref="comment"></textarea><br/>
<button onClick={this.addComment}>发表留言</button>
</div>
)
}
}
export default Board;