import React, { Component } from 'react'
import "./css/App.css"
export default class App extends Component {
state = {
username: '',
txt: '',
list: []
}
// 受控组件
handleChange(ev) {
const target = ev.target;
this.setState({
[target.name]: target.value
})
}
// 渲染留言
renderLiuyan() {
const { list } = this.state;
return list.map((item, index) => (
<li key={ index }>
<span>{item.username}</span>
<span className='content'>{ item.txt }</span>
<button onClick={ () => this.send(index) }>回复</button>
<ul>
{
item.info.map((item2, index2) => (
<li key={ index2 }>{ item2 }</li>
))
}
</ul>
</li>
))
}
// 提交留言
submit() {
const { username, txt, list } = this.state;
this.setState({
list: [ { id: Date.now(), username, txt, info: [] }, ...list ],
username: '',
txt: ''
})
}
// 回复留言
send(idx) {
const copyList = [ ...this.state.list ];
copyList[idx].info.push(this.state.txt);
this.setState({
list: copyList,
txt: ''
})
}
render() {
const { username, txt } = this.state
return (
<div>
<input type="text" name="username" value={ username } onChange={ ev => this.handleChange(ev) } autoComplete='off' /> <br />
<textarea name="txt" value={ txt } onChange={ ev => this.handleChange(ev) }></textarea> <br />
<button onClick={ () => this.submit() }>提交留言</button>
<hr />
<ul>{ this.renderLiuyan() }</ul>
</div>
)
}
}
留言板案例简单版
于 2023-07-14 08:25:37 首次发布