Vue的自定义指令,对应react怎么写
React没有类似于Vue的自定义指令的概念,但是可以通过自定义组件或者高阶组件来实现类似的功能。
自定义组件:可以将需要的逻辑和功能封装在一个组件中,通过props传递参数来控制组件的行为。
高阶组件:可以将需要的逻辑和功能封装在一个函数中,返回一个新的组件,通过props或者context来控制组件的行为。
例如,Vue中的自定义指令v-focus可以用React的高阶组件来实现:
import React, { Component } from 'react';
function withFocus(WrappedComponent) {
return class extends Component {
componentDidMount() {
this.node.focus();
}
render() {
return <WrappedComponent {...this.props} ref={node => (this.node = node)} />;
}
};
}
class Input extends Component {
render() {
return <input type="text" {...this.props} />;
}
}
const InputWithFocus = withFocus(Input);
export default InputWithFocus;
使用方式:
import React from 'react';
import InputWithFocus from './InputWithFocus';
function App() {
return (
<div>
<InputWithFocus placeholder="Enter text here" />
</div>
);
}
export default App;
在这个例子中,withFocus是一个高阶组件,它接收一个组件作为参数,返回一个新的组件,并在新的组件的componentDidMount中调用了focus()方法,使得输入框获取焦点。InputWithFocus是使用高阶组件withFocus创建的新组件,它继承了Input组件的所有props,并将其传递给Input组件。这样,在使用InputWithFocus组件时,就可以将placeholder等props传递给Input组件,同时获得了自动获取焦点的功能。
原文地址: http://www.cveoy.top/t/topic/tLE 著作权归作者所有。请勿转载和采集!