文章目录
- 1、受控组件
-
- 1.1 认识受控组件
- 1.2 checkout
- 1.3 selected
- 1.4 非受控组件
- 2、高阶组件
-
- 2.1 认识高阶组件
- 2.2 应用1-props增强的基本使用
- 2.3 对象增强的应用场景-context共享
- 2.4 应用2-鉴权
- 2.5 应用3 – 生命周期劫持
- 2.6、高阶组件的意义
- 3、Portals
- 4、fragment
- 5、StrictMode
- 6、React过渡动画实现
-
- 6.1 CSSTransition
- 6.2 SwitchTransition
- 6.3 TransitionGroup
1、受控组件
1.1 认识受控组件
import React, { PureComponent } from "react";
export class App extends PureComponent {
constructor() {
super();
this.state = {
userName: "",
};
}
inputChange(e) {
const value = e.target.value;
this.setState({ userName: value });
}
submitChange(e) {
e.preventDefault();
console.log(e);
}
render() {
const { userName } = this.state;
return (
<div>
<form onSubmit={(e) => this.submitChange(e)}>
<label htmlFor="userName">
用户:
<input
id="userName"
type="text"
name="userName"
value={userName}
onChange={(e) => this.inputChange(e)}
></input>
</label>
<button type="submit">注册</button>
</form>
</div>
);
}
}
export default App;
1.2 checkout
import React, { PureComponent } from "react";
export class App extends PureComponent {
constructor() {
super();
this.state = {
userName: "",
password: "",
isAgree: false,
hobbies: [
{ value: "sing", text: "唱", isChecked: false },
{ value: "dance", text: "跳", isChecked: false },
{ value: "rap", text: "rap", isChecked: false },
],
};
}
handleAgreeChange(e) {
this.setState({ isAgree: e.target.checked });
}
handleHobbiesChange(e, index) {
const hobbies = [...this.state.hobbies];
hobbies[index].isChecked = e.target.checked;
this.setState({ hobbies });
}
submitChange(e) {
e.preventDefault();
console.log(e);
const hobbies = this.state.hobbies.filter((item) => item.isChecked);
console.log(hobbies);
}
render() {
const { isAgree, hobbies } = this.state;
return (
<div>
<form onSubmit={(e) => this.submitChange(e)}>
{}
<label htmlFor="agree">
<input
type="checkbox"
id="agree"
checked={isAgree}
onChange={(e) => this.handleAgreeChange(e)}
/>
单选
</label>
{}
<div>
{hobbies.map((item, index) => {
return (
<label htmlFor={item.value} key={index}>
<input
type="checkbox"
id={item.value}
checked={item.isChecked}
onChange={(e) => this.handleHobbiesChange(e, index)}
/>
{item.text}
</label>
);
})}
</div>
<button type="submit">注册</button>
</form>
</div>
);
}
}
export default App;
1.3 selected
import React, { PureComponent } from "react";
export class App extends PureComponent {
constructor() {
super();
this.state = {
fruit: "orange",
fruits: ["orange", "apple"],
};
}
submitChange(e) {
e.preventDefault();
console.log(e);
}
fruitChange(e) {
console.log(e.target.value);
this.setState({ fruit: e.target.value });
}
fruitsChange(event) {
const values = Array.from(
event.target.selectedOptions,
(item) => item.value
);
this.setState({ fruits: values });
}
render() {
const { fruit, fruits } = this.state;
return (
<div>
<form onSubmit={(e) => this.submitChange(e)}>
{}
<select value={fruit} onChange={(e) => this.fruitChange(e)}>
<option value="apple">苹果</option>
<option value="orange">橘子</option>
<option value="banana">香蕉</option>
</select>
{}
<select
value={fruits}
multiple
onChange={(e) => this.fruitsChange(e)}
>
<option value="apple">苹果</option>
<option value="orange">橘子</option>
<option value="banana">香蕉</option>
</select>
<button type="submit">注册</button>
</form>
</div>
);
}
}
export default App;
1.4 非受控组件
import React, { PureComponent, createRef } from "react";
export class App extends PureComponent {
constructor() {
super();
this.state = { intro: "kiki" };
this.introRef = createRef();
}
submitChange(e) {
e.preventDefault();
console.log(e);
console.log(this.introRef.current.value);
}
render() {
const { intro } = this.state;
return (
<div>
<form onSubmit={(e) => this.submitChange(e)}>
<input type="text" defaultValue={intro} ref={this.introRef}></input>
<button type="submit">注册</button>
</form>
</div>
);
}
}
export default App;
2、高阶组件
2.1 认识高阶组件
import React, { PureComponent } from "react";
class HelloWorld extends PureComponent {
constructor(props) {
super(props);
}
render() {
const { name } = this.props;
return (
<div>
<span>普通的类组件-{name}</span>
</div>
);
}
}
const Hoc = (Comp) => {
class NewCpn extends PureComponent {
render() {
return (
<div>
<h1>我是高阶组件</h1>
{}
<Comp name="kiki" />
</div>
);
}
}
return NewCpn;
};
const HelloWorldHOC = Hoc(HelloWorld);
class componentName extends PureComponent {
render() {
return (
<div>
{}
<HelloWorldHOC />
</div>
);
}
}
export default componentName;
2.2 应用1-props增强的基本使用
import React, { PureComponent } from "react";
const enhancedUserInfo = (OriginComponent) => {
class NewComponent extends PureComponent {
constructor(props) {
super(props);
this.state = {
userInfo: {
name: "kiki",
age: "18",
},
};
}
render() {
return <OriginComponent {...this.props} {...this.state.userInfo} />;
}
}
return NewComponent;
};
export default enhancedUserInfo;
import React, { PureComponent } from 'react'
import enhancedUserInfo from '../hoc/enhanced_props'
export class About extends PureComponent {
render() {
return (
<div>About: {this.props.name}</div>
)
}
}
export default enhancedUserInfo(About)
import React, { PureComponent } from "react";
import enhancedUserInfo from "./hoc/enhanced_props";
import About from "./pages/About";
const Home = enhancedUserInfo((props) => {
return (
<h1>
{props.name}-{props.age}
</h1>
);
});
const HelloWord = enhancedUserInfo((props) => {
return (
<h1>
{}
{props.name}-{props.age}-{props.banner}
</h1>
);
});
export class App extends PureComponent {
render() {
return (
<div>
<Home />
{}
<HelloWord banner="['a','b']" />
{}
<About />
</div>
);
}
}
export default App;
2.3 对象增强的应用场景-context共享
import { createContext } from "react";
const themeContext = createContext();
export default themeContext;
import ThemeContext from "../context/theme_context";
const withTheme = (OriginComp) => {
return (props) => {
return (
<ThemeContext.Consumer>
{(value) => {
return <OriginComp {...value} {...props} />;
}}
</ThemeContext.Consumer>
);
};
};
export default withTheme;
import React, { PureComponent } from "react";
import ThemeContext from "../context/theme_context";
import withTheme from "../hoc/with_theme";
export class Product extends PureComponent {
render() {
const { color, size, name } = this.props;
return (
<div>
<h2>
context注入的参数: {color}-{size}
</h2>
<div>传递给product的参数:{name}</div>
</div>
);
}
}
export default withTheme(Product);
import React, { PureComponent } from "react";
import ThemeContext from "./context/theme_context";
import Product from "./pages/Product";
export class App extends PureComponent {
render() {
return (
<div>
<ThemeContext.Provider value={{ color: "red", size: 30 }}>
<Product name="kiki" />
</ThemeContext.Provider>
</div>
);
}
}
export default App;
2.4 应用2-鉴权
const loginAuth = (OriginComp) => {
return (props) => {
const token = localStorage.getItem("token");
return token ? <OriginComp {...props} /> : "请先登录";
};
};
export default loginAuth;
import React, { PureComponent } from 'react'
import loginAuth from '../hoc/login_auth'
export class Cart extends PureComponent {
render() {
return (
<h2>Cart Page</h2>
)
}
}
export default loginAuth(Cart)
import React, { PureComponent } from "react";
import Cart from "./pages/Cart";
export class App extends PureComponent {
handleClick() {
localStorage.setItem("token", "kiki");
this.forceUpdate();
}
render() {
return (
<div>
<button onClick={(e) => this.handleClick()}>点击登录</button>
<Cart />
</div>
);
}
}
export default App;
2.5 应用3 – 生命周期劫持
import { PureComponent } from "react";
function logRenderTime(OriginComponent) {
return class extends PureComponent {
UNSAFE_componentWillMount() {
this.beginTime = new Date().getTime()
}
componentDidMount() {
this.endTime = new Date().getTime()
const interval = this.endTime - this.beginTime
console.log(`当前${OriginComponent.name}页面花费了${interval}ms渲染完成!`)
}
render() {
return <OriginComponent {...this.props}/>
}
}
}
export default logRenderTime
import React, { PureComponent } from 'react'
import logRenderTime from '../hoc/log_render_time'
export class Detail extends PureComponent {
render() {
return (
<div>
<h2>Detail Page</h2>
<ul>
<li>数据列表1</li>
<li>数据列表2</li>
<li>数据列表3</li>
<li>数据列表4</li>
<li>数据列表5</li>
<li>数据列表6</li>
<li>数据列表7</li>
<li>数据列表8</li>
<li>数据列表9</li>
<li>数据列表10</li>
</ul>
</div>
)
}
}
export default logRenderTime(Detail)
import React, { PureComponent } from 'react'
import Detail from './pages/Detail'
export class App extends PureComponent {
render() {
return (
<div>
<Detail/>
</div>
)
}
}
export default App
2.6、高阶组件的意义
3、Portals
4、fragment
import React, { PureComponent, Fragment } from 'react'
export class App extends PureComponent {
constructor() {
super()
this.state = {
sections: [
{ title: "哈哈哈", content: "我是内容, 哈哈哈" },
{ title: "呵呵呵", content: "我是内容, 呵呵呵" },
{ title: "嘿嘿嘿", content: "我是内容, 嘿嘿嘿" },
{ title: "嘻嘻嘻", content: "我是内容, 嘻嘻嘻" },
]
}
}
render() {
const { sections } = this.state
return (
<>
<h2>我是App的标题</h2>
<p>我是App的内容, 哈哈哈哈</p>
<hr />
{
sections.map(item => {
return (
<Fragment key={item.title}>
<h2>{item.title}</h2>
<p>{item.content}</p>
</Fragment>
)
})
}
</>
)
}
}
export default App
5、StrictMode
6、React过渡动画实现
6.1 CSSTransition
npm install react-transition-group --save
import React, { createRef, PureComponent } from "react";
import { CSSTransition } from "react-transition-group";
import "./style.css";
export class App extends PureComponent {
constructor(props) {
super(props);
this.state = {
isShow: true,
};
this.sectionRef = createRef();
}
render() {
const { isShow } = this.state;
return (
<div>
<button onClick={(e) => this.setState({ isShow: !isShow })}>
切换
</button>
{}
{}
{}
{}
<CSSTransition
nodeRef={this.sectionRef}
in={isShow}
unmountOnExit={true}
classNames="why"
timeout={2000}
appear
onEnter={(e) => console.log("开始进入动画")}
onEntering={(e) => console.log("执行进入动画")}
onEntered={(e) => console.log("执行进入结束")}
onExit={(e) => console.log("开始离开动画")}
onExiting={(e) => console.log("执行离开动画")}
onExited={(e) => console.log("执行离开结束")}
>
<div className="section" ref={this.sectionRef}>
<h2>哈哈哈</h2>
<p>我是内容, 哈哈哈</p>
</div>
</CSSTransition>
</div>
);
}
}
export default App;
6.2 SwitchTransition
import React, { PureComponent } from "react";
import { SwitchTransition, CSSTransition } from "react-transition-group";
import "./style.css";
export class App extends PureComponent {
constructor() {
super();
this.state = {
isLogin: true,
};
}
render() {
const { isLogin } = this.state;
return (
<div>
<SwitchTransition mode="out-in">
<CSSTransition
key={isLogin ? "exit" : "login"}
classNames="login"
timeout={1000}
>
<button onClick={(e) => this.setState({ isLogin: !isLogin })}>
{isLogin ? "退出" : "登录"}
</button>
</CSSTransition>
</SwitchTransition>
</div>
);
}
}
export default App;
6.3 TransitionGroup
import React, { PureComponent } from "react";
import { TransitionGroup, CSSTransition } from "react-transition-group";
import "./style.css";
export class App extends PureComponent {
constructor() {
super();
this.state = {
books: [
{ id: 111, name: "你不知道JS", price: 99 },
{ id: 222, name: "JS高级程序设计", price: 88 },
{ id: 333, name: "Vuejs高级设计", price: 77 },
],
};
}
addNewBook() {
const books = [...this.state.books];
books.push({
id: new Date().getTime(),
name: "React高级程序设计",
price: 99,
});
this.setState({ books });
}
removeBook(index) {
const books = [...this.state.books];
books.splice(index, 1);
this.setState({ books });
}
render() {
const { books } = this.state;
return (
<div>
<h2>书籍列表:</h2>
<TransitionGroup component="ul">
{books.map((item, index) => {
return (
<CSSTransition key={item.id} classNames="book" timeout={1000}>
<li>
<span>
{item.name}-{item.price}
</span>
<button onClick={(e) => this.removeBook(index)}>删除</button>
</li>
</CSSTransition>
);
})}
</TransitionGroup>
<button onClick={(e) => this.addNewBook()}>添加新书籍</button>
</div>
);
}
}
export default App;