React杂记

A JavaScript library for building user interfaces

打包空白页

1
2
//package.json
"homepage":"."

绑定事件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//...
render() {
return (
<div className="fade">
{/* <span>{this.state.info}</span> */}
<div className="button" onClick={()=>this.open}>
点击弹窗
</div>
</div>
);
}

open() {
console.log("xixi");
}
//...

条件渲染

单个

1
2
3
{
this.props.poopState && <Poop />;
}

复合

1
2
3
{
this.props.poopState ? <Poop /> : null;
}

修改状态/setState

1
2
3
this.setState({
value: !value
})

Redux 状态管理

环境配置

1
2
npm i redux react-redux -s
`

storeJS 脚本配置

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
/* eslint-disable */
import {
createStore,
combineReducers
} from "redux";

//原始数据池 data pool
let storeState = {
poopState: false
}
// 处理方式 action
const reducer = function (state = storeState, action) {
switch (action.type) {
case 'SET':
return {
...state, [action.payload.key]: action.payload.val
}
break
case 'Switch':
return {
...state, [action.payload.key]: !state[action.payload.key]
}
break
default:
return state
}
}
// define
const store = createStore(
reducer, /* preloadedState, */
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
export default store

indexJS

1
2
3
4
5
6
7
8
9
import { Provider } from "react-redux";
import store from "./store";

ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);

componentsJS

1
2
3
import { connect } from "react-redux";
//...
export default connect(state => state)(Fade);

Transition 过渡

环境配置

1
npm i  react-transition-group -s

脚本配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
render() {
// const [inProp, setInProp] = useState(false);
return (
<div className="fade">
<div className="button" onClick={this.open}>
点击弹窗
</div>
<CSSTransition
in={this.props.poopState}
timeout={200}
classNames="fade"
unmountOnExit
>
<Poop />
</CSSTransition>
</div>
);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
.fade-enter {
opacity: 0;
}

.fade-enter-active {
opacity: 1;
transform: translateX(0);
transition: opacity 200ms, transform 200ms;
}

.fade-exit {
opacity: 1;
}

.fade-exit-active {
opacity: 0;
transition: opacity 200ms, transform 200ms;
}

生命周期函数

1
2
3
4
//mounted
componentDidMount() {}
//unload
componentWillUnmount() {}

列表渲染

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<ul>
{this.props.list.map((e, index) => {
return (
<li
className={["item", e.completed ? "act" : ""].join(" ")}
key={index}
>
<div
className="title"
style={{
color: e.completed ? "#fff" : "",
fontWeight: "bold"
}}
>
{e.title}
</div>
</li>
);
})}
</ul>

监听 event

1
onKeyDown={(e) => this.enter(e)}

获取组件内DOM节点

1
2
<div ref={'dom'} />
console.log(this.refs.dom)