Closed msforest closed 5 years ago
react事件与dom事件相似,但又有一些不同点
<button onclick="activateLasers()">
Activate Lasers
</button>
- react无法使用`return false`来阻止默认行为,必须在函数里明确调用`preventDefault()`
react调用事件需要绑定`this`,否则`this`等于`undefined`
有两种绑定方式:
1,在构造方法里绑定
```javascript
class InputForm extends React.Component{
constructor(props){
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(e){
console.log(e.target.value)
this.setState({value: e.target.value});
}
handleSubmit(e){
console.log(e);
e.preventDefault();
}
render(){
return (
<form onSubmit={this.handleSubmit}>
name: <input type="text" value={this.state.value} onChange={this.handleChange} /><br/>
<input type="submit" value="submit" />
</form>
);
}
}
2,在定义的地方使用函数调用
class Toggle extends React.Component{
constructor(props){
super(props);
this.state = {isToggleOn: true};
}
handlerClick(){
console.log('test')
this.setState(pre=>({
isToggleOn: !pre.isToggleOn
}));
}
render(){
return (
<button onClick={(e)=>this.handlerClick(e)}>{this.state.isToggleOn?'on':'off'}</button>
);
}
}
当需要向函数传递参数时,尽可能使用第二种形式(PS:参数e不需要时可不传)
props对象是作为component的attribute,根据props可以判断component的属性, props是只读的,用于从父组件向子组件传递数据;state是作为component内部的一个property,根据state可以判断内部有哪些变化的值;
<App name="myName" />
class App extends React.Component{
constructor(props){
super(props); //props contain name
this.state = {from: 'zj'};
}
render(){}
}
判断组件是否需要重新渲染
shouldComponentUpdate(nextProps, nextState) {
if (this.props.color !== nextProps.color) {
return true; //更新
}
if (this.state.count !== nextState.count) {
return true;
}
return false; //不更新
}
//和下面代码效果相同
class xxx extends React.PureComponent{
}
React.PureComponent
表示shallow comparison
浅显的比较
分为以下三大块:
Mounting:组件被创建会触发此阶段,将按顺序执行以下方法
state
不会导致组件重新渲染null
或false
state
会导致组件重新渲染;也适合处理DOM操作Updating:props
或state
被更新会触发此阶段,将按顺序执行以下方法,此时组件被重新渲染
mounting
阶段不会触发,只有组件的props
被更新才会触发nextProps
和nextState
两个参数判断是否重新渲染组件this.setState()
shouldComponentUpdate()
返回值控制;Unmounting:组件被移动时会触发此阶段,将按顺序执行以下方法
componentDidMount
阶段创建的DOM元素Error Handling
Router
, Route
, Link
, IndexRoute
, Redirect
.
<Router history={history}>
<Route path='/' component={App}>
<IndexRoute component={Index}/>
<IndexRedirect to='/home' />
<Route path='home' component={Home} onEnter={enter} onLeave={leave} />
<Redirect from='from' to='to' />
</Route>
</Router>
1. React库加载
2. react 知识碎片
3. react Lifecycle
4. react router
React库加载
学习资料: facebook's React 阮一峰React技术栈