学习成果:
1.如何创建组件 :函数组件和类组件,即无状态组件和有状态组件
2.组件在调用函数时的指针问题解决 :在标签内的事件里使用箭头函数 或使用创建函数时需要绑定指针 或 使用class类名创建实例组件 在里面的事件方法用箭头函数(指针问题解决的是能否调用setState的问题)可以把指针绑定到render函数或类实例 因为他们都可以获取到setState方法
3.如何渲染和绑定事件:使用name和value属性进行搭配
4.如何循环表单:使用.map(item =>(这里写入表单结构,如li标签))映射
5.如何使用结构赋值搭配使用 :[{id:xxx,name:xxx,content:xxx},…comments]
6.使用setState()方法更新state
7.组件渲染:ReactDOM.render(<类名 />,document.getElementById(‘xxx’)) 第二个是挂载点
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
class App extends React.Component {
//初始化状态
state = {
comments: [
{ id: 1, name: 'jack', content: '沙发!!' },
{ id: 2, name: 'jac1', content: '沙发!!1' },
{ id: 3, name: 'jac2', content: '沙发!!2' },
],
userName: '',
userContent: '',
}
//输入事件
inputEvent = (e) => {
//用箭头函数来获取render的指针
const { name, value } = e.target
// console.log(name)
this.setState({
[name]: value,
})
}
//点击发表
submit = (e) => {
const { comments, userName, userContent } = this.state
// console.log(userName, userContent)
if (userName.trim() === '' || userContent.trim() === '') {
return alert('请填写信息')
}
const newComments = [
{
id: Math.random(),
name: userName,
content: userContent,
},
...comments,
]
this.setState({
comments: newComments,
userName: '',
userContent: '',
})
}
//渲染评论列表
renderList() {
const { comments } = this.state
if (comments.length === 0) {
return <div className="no-comment">暂无评论,快去评论</div>
}
return (
<ul>
{comments.map((item) => (
<li key={item.id}>
<h3>评论人:{item.name}</h3>
<p>评论内容:{item.content}</p>
</li>
))}
</ul>
)
}
render() {
const { userName, userContent } = this.state
return (
<div className="app">
<div>
<input
className="user"
type="test"
name="userName"
value={userName}
onChange={this.inputEvent}
placeholder="请输入评论人"
></input>
<br />
<textarea
className="content"
cols="30"
rows="10"
name="userContent"
value={userContent}
onChange={this.inputEvent}
placeholder="请输入评论内容"
></textarea>
<br />
<button onClick={this.submit}>发表评论</button>
</div>
{this.renderList()}
{/* {
//三元表达式
this.state.comments.length === 0 ? (
<div className="no-comment">暂无评论,快去评论</div>
) : (
<ul>
{
this.state.comments.map(item => (
<li key={item.id}>
<h3>评论人:{item.name}</h3>
<p>评论内容:{item.content}</p>
</li>
))
}
</ul>
)
} */}
{/* <div className="no-comment">暂无评论,快去评论</div>
<ul>
{
this.state.comments.map(item => (
<li key={item.id}>
<h3>评论人:{item.name}</h3>
<p>评论内容:{item.content}</p>
</li>
))
}
</ul> */}
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('root'))