对于多个React组件,我想向React的生命周期注入(inject)公共(public)代码。
有什么好的办法吗?
var ComponentA = React.createClass({
componentWillMount: function () {
},
componentDidUpdate: function(){
//inject common code
},...
var ComponentB = React.createClass({
componentWillMount: function () {
},
componentDidUpdate: function(){
//inject common code
},...
最佳答案
您的意思是只是在多个组件之间共享功能吗?如果是这样,您可以将它们保存在一个单独的文件中,然后将它们导入到您需要的位置:
// common js
function hello() {
console.log('hello');
}
module.exports = hello;
// your component
var hello = require('./common');
var ComponentA = React.createClass({
componentDidUpdate: function(){
hello();
},//...
http://www.webpackbin.com/Nk80m1x_W
<小时/>您可以做的另一件事是创建一个包装器(高阶)组件:
var WrapperComponent = React.createClass({
componentDidUpdate: function() {
// code you want to inject.
},
render: function () {
return(<div>{this.props.children}</div>);
}
});
然后,每当您需要使用具有该生命周期的组件时,您都可以在 jsx 中执行此操作:
<WrapperComponent>
<ComponentA />
</WrapperComponent>
关于javascript - 如何在 React 组件中注入(inject)通用代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38581588/