Consider the following, I have a reusable component, let's call it myComponent
, myComponent
is used twice, it also has a prop called whenAccepted where in both places where i use the component i run the same function. I would like to outsource that into a new file so I can just import it and run it instead of writing it twice. Any advice for that? I was thinking about HOC's but i'm not sure if it would work as i'll need more stuff, for the function to run it also needs some data present in the both files where I use it. How would you go about that Reactors?
答案 0 :(得分:0)
如果我正确理解了您的问题,则可以通过“我运行相同的函数。我想将其外包给新文件”来提取要在多个组件中使用的函数。这就是我要完成的方式。
./mySharedFunction.js
./MyComponent.js
./MyComponent2.js
// mySharedFunction.js
export default const mySharedFunction = (data) => {
...do stuff...
}
// MyComponent.js
import mySharedFunction from './mySharedFunction.js
export default class MyComponent extends Component {
constructor(props) {
super(props)
mySharedFunction(data)
}
...some code...
render() {
...
}
}
// MyComponent2.js
import mySharedFunction from './mySharedFunction.js
export default class MyComponent2 extends Component {
...some code...
classMethod = (data) => {
mySharedFunction(data)
}
render() {
...
}
}
希望这会有所帮助