Reactjs 来自HOC和组件的反应状态
我有一个表单,通过高阶组件管理受控输入。结构如下: 场高阶分量Reactjs 来自HOC和组件的反应状态,reactjs,jsx,higher-order-components,Reactjs,Jsx,Higher Order Components,我有一个表单,通过高阶组件管理受控输入。结构如下: 场高阶分量 函数基字段(WrappedComponent){ 类WrappedField扩展了React.Component{ 建造师(道具){ 超级(道具); 此.state={ 值:“”, 活动:错误, } } 设置值=(e)=>{ this.setState({value:e.target.value}) } ... .... 领域 从“React”导入React; 从“./BaseField”导入BaseField; 常量文本字段=(
函数基字段(WrappedComponent){
类WrappedField扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
值:“”,
活动:错误,
}
}
设置值=(e)=>{
this.setState({value:e.target.value})
}
...
....
领域
从“React”导入React;
从“./BaseField”导入BaseField;
常量文本字段=(道具)=>{
返回
}
导出默认基本字段(TextField);
使用TextField
时效果很好-但是,我想更灵活地使用它-例如,在某些情况下,我希望能够增强onChange
功能,总是让它设置状态,但也让它根据组件TextField中的状态或函数做其他事情代码>在中使用
我是否误解了HOC的工作原理?您可以使用以下内容:
我的反应是:
export function copyPropsWithout(props, without) {
const propKeys = Object.keys(props);
const passProps = propKeys.reduce((obj, propKey) => {
if (without.indexOf(propKey) === -1) {
obj[propKey] = props[propKey];
}
return obj;
}, {});
return passProps;
}
我会将这些添加到您的UTIL中,然后像这样使用它们:
...
<WrappedComponent
{...copyPropsWithout(this.props, ['onChange'])}
value={this.state.value}
set={createChainedFunction(this.setValue, this.props.onChange}}
active={this.state.active}
/>
....
。。。
....
function createChainedFunction(...funcs) {
return funcs
.filter(f => f != null)
.reduce((acc, f) => {
if (typeof f !== 'function') {
throw new Error('Invalid Argument Type, must only provide functions, undefined, or null.');
}
if (acc === null) {
return f;
}
return function chainedFunction(...args) {
acc.apply(this, args);
f.apply(this, args);
};
}, null);
}
export function copyPropsWithout(props, without) {
const propKeys = Object.keys(props);
const passProps = propKeys.reduce((obj, propKey) => {
if (without.indexOf(propKey) === -1) {
obj[propKey] = props[propKey];
}
return obj;
}, {});
return passProps;
}
...
<WrappedComponent
{...copyPropsWithout(this.props, ['onChange'])}
value={this.state.value}
set={createChainedFunction(this.setValue, this.props.onChange}}
active={this.state.active}
/>
....