方式一:通过Props传递
1.共同的数据放在父组件上,特有的数据放在自己组件内部(state)
2.通过props可以传递一般数据和函数数据,只能一层一层传递
3.一般数据——>父组件传递数据给子组件——>子组件读取数据
4.函数数据——>子组件传递数据给父组件——>子组件调用函数
方式二:使用消息订阅(subscribe)-发布(publish)机制
1.工具库:PubSubJS
2.下载:npm install --save pubsub-js
代码:
import React from 'react'import PubSub from 'pubsub-js'import CommentAdd from '../comment-add/comment-add'import CommentList from '../comment-list/comment-list'export default class App extends React.Component { // 第一种初始化数据对象方法 /* constructor(props) { super(props) this.state = { comments: [ {username: 'Tom', content: 'react挺好的!'}, {username: 'Jack', content: 'react有点难!'} ] } }*/ //第二种初始化数据对象方法,给对象指定state属性 state = { comments: [ {username: 'Tom', content: 'react挺好的!'}, {username: 'Jack', content: 'react有点难!'}, {username: 'Jensen', content: '干就完事儿了!'} ] } componentDidMount() { //订阅消息 PubSub.subscribe('deleteComment', (msg, index) => { this.deleteComment(index) }) } //添加评论 addComment = (comment) => { //得到状态 const {comments} = this.state; //修改状态内容 comments.unshift(comment); //最后更新状态 this.setState({comments}); } //删除指定评论 deleteComment = (index) => { const {comments} = this.state // splice可以进行三种操作,增(index,0,{})、删(index,1)、改(index,1,{}) comments.splice(index, 1); //更新状态 this.setState({comments}); } render() { const {comments} = this.state return () }}请发表对React的评论
import React, {Component} from 'react'import PropTypes from 'prop-types'import CommentItem from '../comment-item/comment-item'import './commentList.css'export default class CommentList extends Component { //指定组件类型. static propTypes = { comments: PropTypes.array.isRequired, }; render() { const {comments, deleteComment} = this.props //判断是显示还是隐藏 const display = comments.length === 0 ? 'block' : 'none' return () }}//这种属性方式有点麻烦/*CommentList.propTypes = { comments: PropTypes.array.isRequired}*/评论回复:
暂无评论,点击左侧添加评论!!!
{ comments.map((c, index) =>
) }
import React, {Component} from 'react';import PropTypes from 'prop-types'import './commentItem.css'import PubSub from 'pubsub-js'export default class CommentItem extends Component { static propTypes = { comment: PropTypes.object.isRequired, index: PropTypes.number.isRequired } handleClick = () => { const {comment, deleteComment, index} = this.props //提示 if (window.confirm(`确定删除${comment.username}的评论吗`)) { //确定后删除 //因为发生了事件,所以这地方是发布消息 PubSub.publish('deleteComment', index) } } render() { const {comment} = this.props return (
{comment.username}说:
{comment.content}