【发布时间】:2019-10-23 20:47:03
【问题描述】:
我正在使用 FormContainer 组件,它接收初始值(基本上是表示输入值的空字符串)和来自父级的 handleSubmit 函数。 FormContainer 具有包含输入值的状态,用于更新状态的 onChange 方法,onSubmit 方法。我正在使用反应上下文将 onChange 传递给输入,并将 onSubmit 传递给提交按钮。
FormContainer 代码:
export const FormContext = React.createContext(null);
class FormContainer extends Component {
constructor(props) {
super(props);
this.state = props.initialValue;
}
onChange(name, value) {
this.setState({ [name]: value });
}
onSubmit(){
const stateKostul = this.state;
console.log(stateKostul);
this.props.handleSubmit(stateKostul);
}
render() {
const value={
formState: this.state,
onChange: (name, value) => this.onChange(name, value),
onSubmit: () =>this.onSubmit(),
};
return (
<FormContext.Provider value={value}>
{this.props.children}
</FormContext.Provider>
);
}
}
我在 AddProductForm 组件/场景中使用它。我还使用 recompose 添加处理程序以获取数据。
AddProductForm代码:
function AddProductForm({ handleSubmit }) {
const initialValue = {
title: '',
location: '',
description: '',
photos: [],
price: '',
};
return (
<div className={s.container}>
<h2 className={s.formTitle}>Add product</h2>
<div className={s.formContainer}>
<FormContainer
initialValue={initialValue}
handleSubmit={handleSubmit}
>
// custom inputs and submit button
</FormContainer>
</div>
</div>
);
}
const enhancer = compose(
withHandlers({
handleSubmit: ({stateKostul}) => () => {
console.log('it works!');
console.log(stateKostul);
//fetch to server
},
}),
);
export default enhancer(AddProductForm);
所以我的问题是我不知道如何将数据从 FormContainer 的状态传递到 AddProductForm。当我将 FormContainer 的状态从道具传递给我的处理程序时,我无法定义。但是从 onSubmit 状态就可以了。
由于 FormContainer 背后的想法,我无法从 FormContainer 获取数据:它应该对任何表单都是通用的。
有什么想法可以在不改变其结构的情况下从 FormContainer 获取数据吗?
【问题讨论】:
标签: javascript reactjs forms react-context recompose