一、简述react事件机制
定制小程序开发费用当用户在为onClick定制小程序开发费用添加函数时,React并没有将Click定制小程序开发费用时间绑定在DOM上面
而是在document定制小程序开发费用处监听所有支持的事件,当事件发生并冒泡至document处时,React将事件内容封装交给中间层SyntheticEvent(负责所有事件合成)
所以当事件触发的时候,对使用统一的分发函数dispatchEvent将指定函数执行。React在自己的合成事件中重写了 stopPropagation方法,将 isPropagationStopped设置为 true,然后在遍历每一级事件的过程中根据此遍历判断是否继续执行。这就是 React自己实现的冒泡机制
二、如何在React中使用innerHTML
增加dangerouslySetInnerHTML属性,并且传入对象的属性名叫_html
function Component(props){ return <div dangerouslySetInnerHTML={{_html:'<span>你好</span>'}}> </div>}
- 1
- 2
- 3
- 4
三、react中的Portal是什么?
Portals 提供了一种很好的将子节点渲染到父组件以外的 DOM 节点的方式。
第一个参数(child)是任何可渲染的 React 子元素,例如一个元素,字符串或碎片。
第二个参数(container)则是一个 DOM 元素。
ReactDOM.createPortal(child, container)
- 1
四、为何React事件要自己绑定this
在 React源码中,当具体到某一事件处理函数将要调用时,将调用 invokeGuardedCallback方法。
function invokeGuardedCallback(name, func, a) { try { func(a); } catch (x) { if (caughtError === null) { caughtError = x; } } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
事件处理函数是直接调用的,并没有指定调用的组件,所以不进行手动绑定的情况下直接获取到的 this是不准确的,所以我们需要手动将当前组件绑定到 this上
五、类组件和函数组件之间的区别是啥?
六、state 和 props 区别是啥?
- state 是组件自己管理数据,控制自己的状态,可变;
- props 是外部传入的数据参数,不可变;
- 没有state的叫做无状态组件,有state的叫做有状态组件;
- 多用 props,少用 state,也就是多写无状态组件。
七、在构造函数调用 super 并将 props 作为参数传入的作用
在调用 super() 方法之前,子类构造函数无法使用this引用,ES6 子类也是如此。
将 props 参数传递给 super() 调用的主要原因是在子构造函数中能够通过this.props来获取传入的 props
传递了props
class MyComponent extends React.Component { constructor(props) { super(props); console.log(this.props); // { name: 'sudheer',age: 30 } } }
- 1
- 2
- 3
- 4
- 5
- 6
没传递 props
class MyComponent extends React.Component { constructor(props) { super(); console.log(this.props); // undefined // 但是 Props 参数仍然可用 console.log(props); // Prints { name: 'sudheer',age: 30 } } render() { // 构造函数外部不受影响 console.log(this.props) // { name: 'sudheer',age: 30 } } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
八、React中的作用是什么?有哪些应用场景?
Refs 提供了一种方式,用于访问在 render 方法中创建的 React 元素或 DOM 节点。Refs 应该谨慎使用,如下场景使用 Refs 比较适合:
- 处理焦点、文本选择或者媒体的控制
- 触发必要的动画
- 集成第三方 DOM 库
Refs 是使用 React.createRef() 方法创建的,他通过 ref 属性附加到 React 元素上。
要在整个组件中使用 Refs,需要将 ref 在构造函数中分配给其实例属性:
class MyComponent extends React.Component { constructor(props) { super(props) this.myRef = React.createRef() } render() { return <div ref={this.myRef} /> }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9