英文:
Using common code without inheritance on RectJS components
问题
以下是您要翻译的内容:
例如,
const Shelf1 = () => {
const mouseDown = (e) => {
console.log("mouseclick");
}
}
const Shelf2 = () => {
const mouseDown = (e) => {
console.log("mouseclick");
}
}
const Shelf3 = () => {
const mouseDown = (e) => {
console.log("mouseclick");
}
}
我想要为这三个组件执行完全相同的功能。
我猜通常我应该创建一个继承类,
然而,有些文章说你不应该在React组件中使用继承。
所以,我只是在思考,我应该用什么来实现这个简单的目的?
一个想法是,创建一个静态类并从每个组件中使用函数,
```javascript
class MyFunc {
static click(){
console.log("mouse click"); // 从每个组件中调用这个函数,比如MyFunc.click();
}
}
然而,我不确定这是否是最佳实践,看起来继承更好。
您能给一些建议吗?
英文:
For example,
const Shelf1 = () =>{
const mouseDown = (e) =>{
console.log("mouseclick");
}
}
const Shelf2 = () =>{
const mouseDown = (e) =>{
console.log("mouseclick");
}
}
const Shelf3 = () =>{
const mouseDown = (e) =>{
console.log("mouseclick");
}
}
I want to do the completely common function for three components.
I guess normally I should make inheritance class,
However some article says you should not use inheritance for react components.
So, I just wondering, what should I use for this simple purpose?
One idea is, making a static class and use function from each components,
class MyFunc {
static click(){
console.log("mouse click"); // call this from each components like MyFunc.click();
}
}
However I am not sure it is the best practice, It looks like inferitance is better.
Could you give some advices?
答案1
得分: 3
以下是翻译好的内容:
- HoC风格 - 这使得另一个组件对子组件有很高的控制权。
const addMouseDownEvents = (Component, config) => props => {
return <Component {...props} onMouseDown={onMouseDown}/>
}
- Hooks风格 - 可重复使用且灵活。您可以将这些函数组合在一起。例如,组件具有一个onMouseDown事件,该事件调用了hook的onMouseDown事件。
const useMouseDown = config => {
const onMouseDown = () => {...}
return {
onMouseDown
}
}
const MyComponent = props => {
const { onMouseDown } = useMouseDown();
....
}
我强烈建议使用hooks模式,因为它是最可重用且最易于使用的。只有在需要在DOM中重复使用可视元素时才需要使用HoC。
英文:
Static code would be the last options that I would choose. Here are some common patterns that you will find used in modern libraries
- HoC style - this gives another component a very high level of control over the sub components
const addMouseDownEvents = (Component,config) => props => {
return <Component {...props} onMouseDown={onMouseDown}/>
}
- Hooks style - reusable and flexible. You can compose the functions together. IE the component has a onMouseDown event that calls the hook's onMouseDown event
const useMouseDown = config => {
const onMouseDown = () => {...}
return {
onMouseDown
}
}
const MyComponent = props => {
const { onMouseDown } = useMouseDown();
....
}
I would strongly recommend using the hooks pattern since it is the most re-usable and easiest to use. HoCs are only needed if there needs to be a visual element in the DOM re-used.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论