父组件传了一个initList
的方法给子组件<ComBox>
,然后子组件可以执行父组件的方法,
从而达到刷新的效果
render() {
return <div style={{width: "100%", padding: "20px", border: "1px solid #ccc", boxSizing: "border-box"}}>
<h1>评论列表</h1>
<ComBox reload={this.initList}></ComBox>
{this.state.list.map((item, index) => {
return <ComItem key={'comitem-'+index} {...item}></ComItem>
})}
</div>
}
// 初始化评论列表数据
initList = () => {
let list = JSON.parse(localStorage.getItem('cmsList') || '[]')
this.setState({
list
})
}
子组件接收父组件的initList
方法并执行
// 重新刷新评论列表
this.props.reload()
demo效果图:
代码
父组件ComList.jsx:
import React from 'react'
import ComItem from './ComItem.jsx'
import ComBox from './ComBox.jsx'
export default class ComList extends React.Component {
constructor(props) {
super(props)
this.state = {
list: [
{user: 'lxm', content: '自由评论1'},
{user: 'czx', content: '自由评论2'},
{user: 'dada', content: '自由评论3'},
]
}
}
render() {
return <div style={{width: "100%", padding: "20px", border: "1px solid #ccc", boxSizing: "border-box"}}>
<h1>评论列表</h1>
<ComBox reload={this.initList}></ComBox>
{this.state.list.map((item, index) => {
return <ComItem key={'comitem-'+index} {...item}></ComItem>
})}
</div>
}
componentDidMount() {
// 获取list
this.initList()
}
// 初始化评论列表数据
initList = () => {
let list = JSON.parse(localStorage.getItem('cmsList') || '[]')
this.setState({
list
})
}
}
子组件ComItem.jsx
import React from 'react'
export default class ComItem extends React.Component {
constructor(props) {
super(props)
}
render() {
return <div>
<h3>评论人: {this.props.user}</h3>
<p>评论内容: {this.props.content}</p>
</div>
}
}
子组件ComBox.jsx
import React from 'react'
export default class ComBox extends React.Component {
constructor(props) {
super(props)
this.state = {
}
}
render() {
return <div style={{display: 'flex', flexDirection: 'column'}}>
<label>评论人</label>
<input type="text" name="user" style={{outline: "none"}} ref="user"/>
<label>评论内容</label>
<textarea name="content" cols="30" rows="3" style={{outline: "none"}} ref="content"></textarea>
<input type="button" value="提交" onClick={this.postComments} style={{width: "40px", border: "none", marginTop: "20px", backgroundColor: "blue", color: "#fff"}}/>
</div>
}
postComments = () => {
// 保存评论
let comments = JSON.parse(localStorage.getItem('cmsList') || '[]')
comments.unshift({user: this.refs.user.value, content: this.refs.content.value})
localStorage.setItem('cmsList', JSON.stringify(comments))
// 刷新输入框
this.refs.user.value = this.refs.content.value = ''
// 重新刷新评论列表
this.props.reload()
}
}
main.js引入进行渲染
import React from 'react'
import ReactDOM from 'react-dom'
import ComList from './components/comments/ComList.jsx'
ReactDOM.render(
<ComList />,
document.getElementById('app')
)