【发布时间】:2020-01-06 08:16:51
【问题描述】:
我昨天问了这个问题:React sharing method across components
import React from 'react';
class LoginForm extends React.Component {
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
const target = e.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
由于我在整个应用程序中多次重复使用handleChange(e),因此我决定将其分离成一个高阶组件,如下所示:
import React from 'react';
const withHandleChange = (WrappedComponent) => {
return class extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
handleChange = e => {
const target = e.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
render() {
return (
<WrappedComponent
handleChange={this.handleChange}
form={this.state}
{...this.props}
/>
);
}
}
};
export default withHandleChange;
我现在没有让LoginForm 维护输入字段的状态,而是让HOC 完成了这项工作,并将这个状态作为一个名为form 的道具传递下去。我还将handleChange 方法作为道具传递下去。
在原始的LoginForm 组件中,我渲染了以下内容:
<input type="text" placeholder="Email" name="email" value={this.props.form.email} onChange={this.props.handleChange} />
我将LoginForm 包装成这样:
const WrappedLoginForm = withHandleChange(LoginForm);
const LoginBox = props => (
<div className="login-box">
<WrappedLoginForm />
</div>
);
这是一个有效的实现吗?我主要关心的两个问题是(1)在withHandleChange 定义中将状态作为道具传递给WrappedComponent,以及(2)渲染WrappedLoginForm,因为我读过你不应该在渲染方法中使用HOC。
至于(1),这是否有效?有没有更好的方法来完成我正在做的事情?
至于 (2),我认为他们的意思是我不应该在 render 方法中运行 HOC 函数,而只是使用包装的组件(就像我现在所做的那样)应该没问题。不过,我有点困惑,希望得到一些确认。
任何和所有建议都会有所帮助。谢谢!
【问题讨论】:
-
输入是否需要将状态保存在某处?表单可以在触发
onSubmit时获取值吗?更改处理程序是非常常见的地方,但我认为它们几乎不值得提取到 HOC 中。不过,要回答您的问题,是的,这似乎是有效的实现,我想我可能已经选择了功能组件。对于 (1) 它装饰了一个组件,因此 props 被传递给被包装的组件。对于 (2),我不太确定我是否遵循,或者存在什么问题。
标签: javascript reactjs higher-order-functions react-component