MJingv / jehol-person-blog

Jehol's Blog 🙋 (hexo+react)
https://mjingv.github.io/JeholBlog/
0 stars 1 forks source link

About React 🍉 #71

Open MJingv opened 3 years ago

MJingv commented 3 years ago

React实践中的问题合集

Q1:如何在map中正确绑定事件(this)

https://www.freecodecamp.org/news/the-best-way-to-bind-event-handlers-in-react-282db2cf1530/

https://reactjs.org/docs/faq-functions.html

  1. bind(执行时确定this): 缺点: rerender
    list.map(i=><div onClick={this.callback.bind(this,xxx)}/>)
  2. constructor 中 bind
    constructor{
    this.callback = this.callback.bind(this);  
    }
    list.map(i=><div onClick={this.callback}/>)
  3. 箭头函数(定义时确定this): 避免在render中使用箭头函数
    
    const callback=(e)=>console.log(e)
    list.map(i=><div onClick={this.callback}/>)

list.map(i=><div onClick={()=>console.log(xx)}/>) //⛔️ will re-render

 4. 绑定父级事件:
```js
const callback=(e)=>{
  e.target //实际元素
  e.currentTarget //父元素
}
<div onClick={this.callback}>
  {
   list.map(i=><div data-tag={i}/>)
  }
</div>

Q2:react中的 this

https://zhuanlan.zhihu.com/p/37911534

  1. 如果你使用了 ES6 的 class 语法,所有在 class 中声明的方法都会自动地使用严格模式
    严格模式:this 找不到是 undefined
    非严格模式:this 找不到是全局对象 global(node) / window (browser)
  2. 复习 this 指向
MJingv commented 3 years ago

About JSX

jsx编译

React.createElement(component, props, ...children)

<MyButton color="blue" shadowSize={2}>
  Click Me
</MyButton>

//compiles into

React.createElement(
  MyButton,
  {color: 'blue', shadowSize: 2},
  'Click Me'
)

jsx规则

const components = { photo: PhotoStory, video: VideoStory };

function Story(props) { // Correct! JSX type can be a capitalized variable. const SpecificStory = components[props.storyType]; return ; }

### children 展示
- string(html)
- jsx
- function children

### others
- Booleans, Null, Undefined 忽略
- 0 会展示
```js
list.length&&<div/>//❌
list.length>0&&<div/>//✅

https://reactjs.org/docs/jsx-in-depth.html#user-defined-components-must-be-capitalized

MJingv commented 3 years ago

state

MJingv commented 3 years ago

生命周期

mouting

updating

unmounting

error

others

总结


https://reactjs.org/docs/react-component.html https://programmingwithmosh.com/javascript/react-lifecycle-methods/ https://imweb.io/topic/5b8cacaa7cd95ea863193572

MJingv commented 3 years ago

受控组件 vs 非受控组件


https://zh-hans.reactjs.org/docs/uncontrolled-components.html