React-CommonBox


title: React-CommentBoxdate: 2020-05-08 11:44:09

tags: React

综合实例-留言本

状态提升和单向数据流

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//App.js
//将状态提升至App.js
import React from "react";
import CommentBox from "./components/CommentBox";
import CommentList from "./components/Commentlist";

class App extends Component {
constructor(props) {
super(props);
this.state = {
commments: ["this id my first reply"],
};
this.addComment = this.addComment.bind(this);
}

addComment(comment) {
this.setState({
comments: [...this.state.comment, comment],
});
}

render() {
const { comments } = this.state;
return (
<div className="App">
<CommentList comments={comments} />
<CommentBox
commentsLength={comments.length}
onAddComment={this.addComment}
/>
</div>
);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//CommentList.js
import React from "react";

const CommentList = ({ comments }) => {
return (
<div className="comment-list-component">
<label>评论列表</label>
<ul className="list-group">
{comments.map((comment, index) => (
<li key={index} className="list-group-item">
{comment}
</li>
))}
</ul>
</div>
);
};

export default CommentList;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//CommentBox.js
import React from 'react'

class CommentBox from React.Component {
constructor(props){
super(props)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleSubmit(event){
alert(this.textInput.value)
event.preventDefault()
}

render(){
return (
<form onSubmit={this.handleSumit}>
<div>
<label>留言内容</label>
<input
type="text"
className="form-control"
placeholder="请输入评论"
ref={(textInput) => {this.textInput = textInput}}
/>
</div>
<button type="submit">
留言
</button>
<p>已有{this.props.commentLength = {this}}条评论</p>
</form>
)
}
}

总结

React 开发思想以及和其他思想的异同

  • 状态提升
  • 自上而下的数据流
  • 和双向绑定的区别