上篇简单介绍了react环境搭建和本地项目的创建,接下来,我们通过一些基础简单的小例子来继续学习react.
渲染组件
引入material-ui框架的组件
头部引入 material-ui 组件
import Button from '@material-ui/core/Button'
在需要渲染的地方引入组件:
<Button variant="contained" color="secondary">
demo 00 添加一个按钮 粉红色的按钮好看吗?
</Button>
引入自定义的组件
src/Demo.js
中创建二个不同类型的组件:
class Demo01 extends React.Component {
// es6组件
render() {
return <p>{this.props.name}</p>;
}
}
function Fundemo(props) {
// 函数组件
return <div>{props.name}</div>
}
src/App.js
中引入他们:
<Demo01 name="class组件属性的赋值"></Demo01>
<Fundemo name="Fundemo组件接收的父组件的传值"></Fundemo>
生命周期及状态
生命周期
componentWillMount()组件挂载,componentWillUnmount() 组件卸载,比较常用的方法,用来处理组件中的数据和状态的初始化.
state 状态机
state就是一个字典,连接上下组件负责组件间简单的通信.
定一个组件,具体可以看代码中各个方法和属性的应用和引用.
class Demo02 extends React.Component {
constructor(props) {
super(props);
this.state = { data: new Date(),data_a : new Date(),};
}
componentWillMount() {
// 组件挂载
this.timerID = setInterval(() => this.tick(),1000)
}
componentWillUnmount() {
// 组件卸载
clearInterval(this.timerID)
}
tick(){
this.setState(
{data_a: new Date()}
)
}
render() {
return (
<div>
<p>在构建函数constructor()中初始化this.state</p>
<p>现在的时间是:{this.state.data.toLocaleString()}</p>
<p>组件的生命周期有三个状态:</p>
<p> Mounting(挂载):
已插入真实 DOM
Updating(更新):正在被重新渲染
Unmounting(卸载):已移出真实 DOM</p>
<Button variant="contained" color="primary">现在的时间是:{this.state.data_a.toLocaleString()}</Button>
</div>
);
}
}
最后引入到App.js
:
其中上图画框的位置,时间是一只在变化的.
事件处理
在构建函数constructor()
中绑定回调函式
this.handleClick = this.handleClick.bind(this);
回调函数:
// 回调函数
handleClick(){
this.setState(state =>({
isTogglenOn:!state.isTogglenOn
}));
}
在组件中绑定事件,注意是字符串:
<Button variant="contained" color="primary" onClick={this.handleClick}>
{this.state.isTogglenOn ? "on" : "off"}
</Button>
效果就是点击按钮文字会来回切换
条件渲染
React 中的条件渲染和 JavaScript 中的一样,使用 JavaScript 运算符 if 或者条件运算符去创建元素来表现当前的状态,然后让 React 根据它们来更新 UI。可以通过javascrip的if else
分支,也可以三目运算等方式.
三目运算
function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
return (
isLoggedIn ? <UserGreeting /> : <GuestGreeting />
)
}
条件分支
if (isLoggedIn) {
btn = <LogoutBtn onClick={this.handleLogoutClick} />;
} else {
btn = <LoginBtn onClick={this.handleLoginClick} />;
}
展示效果
未登录的时候:
已登陆的情况下:
列表渲染
react渲染多个循环组件使用JavaScript中的map()方法遍历数组,然后循环渲染.
元素的 key 只有放在就近的数组上下文中才有意义。
class Demo05 extends React.Component {
constructor(props) {
super(props);
this.state = {
posts : [
{id: 1, title: 'Hello World', content: 'Welcome to learning React!'},
{id: 2, title: 'Installation', content: 'You can install React from npm.'}
]
}
}
render(){
const content = this.state.posts.map((post) =>
<div key={post.id}>
<h2>{post.title}</h2>
<p>{post.content}</p>
</div>
)
return(
<div>{content}</div>
) }
}
最终效果遍历打印出数组中的标题和内容.
一个简单的表单
表单的操作主要是数据的获取和事件的绑定, 当需要处理多个 input 元素时,我们可以给每个元素添加 name 属性,并让处理函数根据 event.target.name 的值选择要执行的操作。
具体代码如下:
import React from 'react';
import Box from '@mui/material/Box';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
class FormDemo extends React.Component {
constructor(props) {
super(props);
this.state = {
username: 'Jack',
password: '12345678',
};
// 绑定输入框字符变化事件,绑定按钮点击事件
this.handleInputChange = this.handleInputChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this)
}
// 当需要处理多个 input 元素时,我们可以给每个元素添加 name 属性,
// 并让处理函数根据 event.target.name 的值选择要执行的操作。
handleInputChange(event) {
const target = event.target;
const value = target.value;
const name = target.name;
this.setState({
[name]: value
});
}
handleSubmit(event) {
event.preventDefault();
alert('提交的名字: ' + this.state.username + '\r\n' + this.state.password);
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<Box
sx={{
'& .MuiTextField-root': { m: 1, width: '25ch'},
}}
noValidate
autoComplete="off"
>
{/* <div><input type="text" value={this.state.username} onChange={this.handleChange} /></div> */}
<div><TextField name="username" type="text" defaultValue={this.state.username} onChange={this.handleInputChange} id="outlined-basic" label="username" variant="outlined" /></div>
<div><TextField name="password" type="password" defaultValue={this.state.password} onChange={this.handleInputChange} id="outlined-basic" label="password" variant="outlined" /></div>
<div><Button type="submit" value="提交" variant="contained" color="primary">提交</Button></div>
</Box>
</form >
)
}
}
export default FormDemo
效果图:
以上demos代码仓库地址:
gihub:demos代码仓库