context
API解决上述问题import React from 'react';
import ReactDOM from 'react-dom';
let ThemeContext = React.createContext();
class Title extends React.Component {
static contextType = ThemeContext
render() {
return (
<div style={{ border: `5px solid ${this.context.color}` }}>
Title
</div>
)
}
}
class Header extends React.Component {
static contextType = ThemeContext
render() {
return (
<div style={{ border: `5px solid ${this.context.color}` }}>
Header
<Title />
</div>
)
}
}
class Content extends React.Component {
static contextType = ThemeContext
render() {
return (
<div style={{ border: `5px solid ${this.context.color}` }}>
Content
<button onClick={() => this.context.changeColor('red')}>变红</button>
<button onClick={() => this.context.changeColor('green')}>变绿</button>
</div>
)
}
}
class Main extends React.Component {
static contextType = ThemeContext
render() {
return (
<div style={{ border: `5px solid ${this.context.color}` }}>
Main
<Content />
</div>
)
}
}
class Panel extends React.Component {
state = { color: 'green' }
changeColor = (color) => {
this.setState({ color });
}
render() {
let value = { color: this.state.color, changeColor: this.changeColor };
//Provider提供者,它负责向下层所有的组件提供数据value
return (
<ThemeContext.Provider value={value}>
<div style={{ border: `5px solid ${this.state.color}`, width: 300 }}>
Panel
<Header />
<Main />
</div>
</ThemeContext.Provider>
)
}
}
ReactDOM.render(<Panel />, document.getElementById('root'));
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
let ThemeContext = React.createContext('theme');
class Header extends Component {
render() {
return (
<ThemeContext.Consumer>
{
value => (
<div style={{ border: `5px solid ${value.color}`, padding: 5 }}>
header
<Title />
</div>
)
}
</ThemeContext.Consumer>
)
}
}
class Title extends Component {
static contextType = ThemeContext;
render() {
return (
<ThemeContext.Consumer>
{
value => (
<div style={{border: `5px solid ${value.color}` }}>
title
</div>
)
}
</ThemeContext.Consumer>
)
}
}
class Main extends Component {
static contextType = ThemeContext;
render() {
return (
<ThemeContext.Consumer>
{
value => (
<div style={{ border: `5px solid ${value.color}`, margin: 5, padding: 5 }}>
main
<Content />
</div>
)
}
</ThemeContext.Consumer>
)
}
}
class Content extends Component {
static contextType = ThemeContext;
render() {
return (
<ThemeContext.Consumer>
{
value => (
<div style={{border: `5px solid ${value.color}`, padding: 5 }}>
Content
<button onClick={() =>value.changeColor('red')} style={{color:'red'}}>红色</button>
<button onClick={() => value.changeColor('green')} style={{color:'green'}}>绿色</button>
</div>
)
}
</ThemeContext.Consumer>
)
}
}
class Page extends Component {
constructor() {
super();
this.state = { color: 'red' };
}
changeColor = (color) => {
this.setState({ color })
}
render() {
let contextVal = {changeColor: this.changeColor,color:this.state.color };
return (
<ThemeContext.Provider value={contextVal}>
<div style={{margin:'10px', border: `5px solid ${this.state.color}`, padding: 5, width: 200 }}>
page
<Header />
<Main />
</div>
</ThemeContext.Provider>
)
}
}
ReactDOM.render(<Page />, document.querySelector('#root'));
function createContext() {
let value;
class Provider extends React.Component {
constructor(props) {
super(props);
value = props.value
this.state = {};
}
static getDerivedStateFromProps(nextProps, prevState) {
value = nextProps.value;
return {};
}
render() {
return this.props.children;
}
}
class Consumer extends React.Component {
constructor(props) {
super(props);
}
render() {
return this.props.children(value);
}
}
return {
Provider,
Consumer
}
}
let ThemeContext = createContext('theme');
const NewComponent = higherOrderComponent(OldComponent)
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class App extends Component {
componentWillMount() {
this.start = Date.now();
}
componentDidMount() {
console.log((Date.now() - this.start) + 'ms')
}
render() {
return <div>App</div>
}
}
ReactDOM.render(<App />, document.getElementById('root'));
import React,{Component} from 'react';
import ReactDOM from 'react-dom';
const logger = (WrappedComponent) => {
class LoggerComponent extends Component {
componentWillMount(){
this.start = Date.now();
}
componentDidMount(){
console.log((Date.now() - this.start)+'ms')
}
render () {
return <WrappedComponent />
}
}
return LoggerComponent;
}
let Hello = logger(props=><h1>hello</h1>);
ReactDOM.render(<Hello />, document.getElementById('root'));
import React,{Component} from 'react';
import ReactDOM from 'react-dom';
const fromLocal = (WrappedComponent,name) =>{
class NewComponent extends Component{
constructor(){
super();
this.state = {value:null};
}
componentWillMount(){
let value = localStorage.getItem(name);
this.setState({value});
}
render(){
return <WrappedComponent value={this.state.value}/>
}
}
return NewComponent;
}
const UserName = ({value})=>(
<input defaultValue = {value}/>
)
const UserNameFromLocal = fromLocal(UserName,'username');
ReactDOM.render(<UserNameFromLocal />, document.getElementById('root'));
import React,{Component} from 'react';
import ReactDOM from 'react-dom';
const fromLocal = (WrappedComponent,name) =>{
class NewComponent extends Component{
constructor(){
super();
this.state = {id:null};
}
componentWillMount(){
let id = localStorage.getItem(name);
this.setState({id});
}
render(){
return <WrappedComponent id={this.state.id}/>
}
}
return NewComponent;
}
const fromAjax = (WrappedComponent) =>{
class NewComponent extends Component{
constructor(){
super();
this.state = {value:{}};
}
componentDidMount(){
fetch(`/${this.props.id}.json`).then(response=>response.json()).then(value=>{
this.setState({value});
});
}
render(){
return <WrappedComponent value={this.state.value}/>
}
}
return NewComponent;
}
const UserName = ({value})=>{
return <input defaultValue = {value.username}/>;
}
const UserNameFromAjax = fromAjax(UserName);
const UserNameFromLocal = fromLocal(UserNameFromAjax,'id');
ReactDOM.render(<UserNameFromLocal />, document.getElementById('root'));
translate.json
{
"zhangsan": "张三"
}
render prop
是指一种在 React 组件之间使用一个值为函数的 prop 共享代码的简单技术<DataProvider render={data => (
<h1>Hello {data.target}</h1>
)}/>
class MouseTracker extends React.Component {
constructor(props) {
super(props);
this.state = { x: 0, y: 0 };
}
handleMouseMove = (event) => {
this.setState({
x: event.clientX,
y: event.clientY
});
}
render() {
return (
<div onMouseMove={this.handleMouseMove}>
<h1>移动鼠标!</h1>
<p>当前的鼠标位置是 ({this.state.x}, {this.state.y})</p>
</div>
);
}
}
class MouseTracker extends React.Component {
constructor(props) {
super(props);
this.state = { x: 0, y: 0 };
}
handleMouseMove = (event) => {
this.setState({
x: event.clientX,
y: event.clientY
});
}
render() {
return (
<div onMouseMove={this.handleMouseMove}>
{this.props.children(this.state)}
</div>
);
}
}
ReactDOM.render(< MouseTracker >
{
props=>(
<>
<h1>移动鼠标!</h1>
<p>当前的鼠标位置是 ({props.x}, {props.y})</p>
</>
)
}
</ MouseTracker>, document.getElementById('root'));
import React,{Component} from 'react';
import ReactDOM from 'react-dom';
class MouseTracker extends React.Component {
constructor(props) {
super(props);
this.state = { x: 0, y: 0 };
}
handleMouseMove = (event) => {
this.setState({
x: event.clientX,
y: event.clientY
});
}
render() {
return (
<div onMouseMove={this.handleMouseMove}>
{this.props.render(this.state)}
</div>
);
}
}
ReactDOM.render(< MouseTracker render={params=>(
<>
<h1>移动鼠标!</h1>
<p>当前的鼠标位置是 ({params.x}, {params.y})</p>
</>
)} />, document.getElementById('root'));
class MouseTracker extends React.Component {
constructor(props) {
super(props);
this.state = { x: 0, y: 0 };
}
handleMouseMove = (event) => {
this.setState({
x: event.clientX,
y: event.clientY
});
}
render() {
return (
<div onMouseMove={this.handleMouseMove}>
{this.props.render(this.state)}
</div>
);
}
}
function withMouse(Component){
return (
(props)=><MouseTracker render={mouse=><Component {...props} {...mouse}/>}/>
)
}
let App = withMouse(props=>(
<>
<h1>移动鼠标!</h1>
<p>当前的鼠标位置是 ({props.x}, {props.y})</p>
</>
));
ReactDOM.render(<App/>, document.getElementById('root'));
ReactDOM.createPortal(child, container)
index.html
<div id="modal-root"></div>
index.js
import React,{Component} from 'react';
import ReactDOM from 'react-dom';
import './modal.css';
class Modal extends Component{
constructor() {
super();
this.modal=document.querySelector('#modal-root');
}
render() {
return ReactDOM.createPortal(this.props.children,this.modal);
}
}
class Page extends Component{
constructor() {
super();
this.state={show:false};
}
handleClick=() => {
this.setState({show:!this.state.show});
}
render() {
return (
<div>
<button onClick={this.handleClick}>显示模态窗口</button>
{
this.state.show&&<Modal>
<div id="modal" className="modal">
<div className="modal-content" id="modal-content">
内容
<button onClick={this.handleClick}>关闭</button>
</div>
</div>
</Modal>
}
</div>
)
}
}
ReactDOM.render(<Page/>,document.querySelector('#root'));
modal.css
.modal{
position: fixed;
left:0;
top:0;
right:0;
bottom:0;
background: rgba(0,0,0,.5);
display: block;
}
@keyframes zoom{
from{transform:scale(0);}
to{transform:scale(1);}
}
.modal .modal-content{
width:50%;
height:50%;
background: white;
border-radius: 10px;
margin:100px auto;
display:flex;
flex-direction: row;
justify-content: center;
align-items: center;
animation: zoom .6s;
}