在React中,我们经常需要在组件之间传递数据或者引用。Ref是一种用于引用React组件或DOM元素的机制。在本文中,我们将详细讨论在Class组件和函数组件之间传递Ref的方式,以及如何在高阶组件(HOC)中传递Ref。
Class组件中的Ref传递:
在Class组件中,我们可以通过使用
React.createRef()
方法创建一个Ref对象。然后,我们可以通过将Ref对象赋值给组件的
ref
属性来传递Ref。
下面是一个简单的示例,演示了如何在Class组件之间传递Ref:
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.childRef = React.createRef();
handleClick = () => {
this.childRef.current.focus();
render() {
return (
<ChildComponent ref={this.childRef} />
<button onClick={this.handleClick}>Focus Input</button>
class ChildComponent extends React.Component {
focus() {
this.input.focus();
render() {
return <input ref={(input) => (this.
高阶
组件
是扩展
组件
功能的绝佳
方式
。 但是高阶
组件
有一个令人讨厌的问题——我们无法访问包装
组件
。 这个小模块试图解决这个问题。
为什么需要访问包装的
组件
?
我正在使用 ES6 装饰器来包装我的“哑”
组件
。 有时我想渲染没有任何装饰器的纯“哑”
组件
。 这个模块让我可以访问纯
组件
。
什么是“哑”
组件
?
应用程序接口
import {
hoc
Decorator , getWrappedComponent } from '
hoc
' ;
const smartComponentDecorator =
hoc
Decorator ( Component =>
class
SmartComponent {
render ( ) {
return < Component> ;
} ) ;
@ smartComponentDecora
注射羽毛服务
import feathers from 'feathers-client' ;
import { reducer as feathersReducer } from 'react-feathers' ;
import { FeathersProvider } from 'react-feathers' ;
import { combineReducers } from 'redux' ;
// configure redux
const roo
使用withContextAsProps
import { withContextAsProps } from 'react-context-consumer-
hoc
'
// ContextA == { a: 1 } && ContextB == { b: 1 }
const InnerComponent = ( { a , b , ... ownProps } ) => { /* ... */ }
const MyComponent = withContextAsProps ( ContextA , ContextB ) ( InnerComp
Lite Form 实现了一个类似 Formik 的 API,所以尝试使用它。 有关更多信息,请参阅。
import { LitElement , html } from 'lit-element'
import { withForm } from 'lite-form'
class
MyForm extends LitElement {
static get properties ( ) {
return {
values : { type : Object } ,
errors : { type : Object } ,
touched : { type : Object }
render ( ) {
retur
React
组件
的onClickOutside包装器
:warning_selector: 该软件包需要您的支持以保持不变。 如果您所在的组织的网站比使用自己的代码解决方案更好,而使用react-onclickoutside更好,请考虑与您的经理联系, 提供。 开源是免费使用的,但肯定不是免费开发的。 如果您有办法奖励所依靠的工作,请考虑这样做。 :warning_selector:
这是一个React高阶
组件
(
HOC
),如果您想让它们侦听文档中元素之外的某个位置(例如,如果您需要隐藏一个人们在页面上其他任何地方单击时的菜单)。
请注意,此
HOC
依赖于.
class
List属性,所有现代浏览器均支持.
class
List属性,但IE等已弃用和过时的浏览器