我正在做一个项目,需要向潜在客户发送一封关于他们感兴趣的房产的电子邮件。有一个顶级组件可以从数据库中获取房产信息和潜在客户的联系信息并传递给它的孩子。有两个组件共享相同的格式化信息过程,然后调用发送电子邮件的电子邮件函数。一个组件的示例如下所示:
import sendEmail from 'actions/sendEmail'
class PropertyDetail extends React.Componet {
state = {
unit: undefined,
prospect: undefined,
};
componentDidMount = () => {
this.setState({
unit: this.props.unit,
prospect: this.props.prospect,
});
};
sendEmail = ({ id, address, prospect }) => {
// quite a bit more gets formatted and packaged up into this payload
const payload = {
id,
address,
prospectEmail: prospect.email,
};
emailFunction(payload);
};
handleEmail = () => {
sendEmail(this.state);
};
render() {
return (
<div>
<h1>{this.state.unit.address}</h1>
<p>Send prospect an email about this property</p>
<button onClick={this.handleEmail}>Send Email</button>
</div>
);
}
}
另一个组件看起来像这样
class UpdateShowing extends React.Component {
state = {
unit: undefined,
prospect: undefined,
showingTime: undefined,
};
componentDidMount = () => {
this.setState({
unit: this.props.unit,
propsect: this.props.prospect,
showingTime: this.props.showingTime,
});
};
sendEmail = ({ id, address, prospectEmail }) => {
// quite a bit more gets formatted and packaged up into this payload
const payload = {
id,
address,
prospectEmail,
};
emailFunction(payload);
};
handleUpdate = newTime => {
// get the new date for the showing ...
this.setState({
showingTime: newTime,
});
// call a function to update the new showing in the DB
updateShowingInDB(newTime);
sendEmail(this.state);
};
render() {
return (
<div>
<p>Modify the showing time</p>
<DatePickerComponent />
<button onClick={this.handleUpdate}>Update Showing</button>
</div>
);
}
}
所以我看到了一些共享功能,我不想在每个组件中重复这些功能。我还在学习(我的第一份工作),为什么不以此为契机来提高我的技能呢?所以我想在 HOC/Render 道具模式上做得更好,但我不确定这是否是使用它的地方。
我应该使用渲染道具创建一个组件(我宁愿使用这种模式而不是 HOC)?我什至不确定那会是什么样子,我已经阅读了博客并观看了会谈,唉
<MouseMove render={(x, y) => <SomeComponent x={x} y={y} />} />
但是这种模式是否适用于我的情况,或者我最好定义一些 lib 函数来处理格式化电子邮件的有效负载,然后将该函数导入到需要它的各种组件中?
谢谢!