react實現留言板功能
阿新 • • 發佈:2020-12-21
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;