【发布时间】:2017-07-03 13:02:55
【问题描述】:
给定以下 React 组件:
class MyComponent extends Component {
sayGreeting = () => {
return this.props.greeting;
}
render() {
return (
<div>{this.sayGreeting()}</div>
);
}
}
greeting 通过 props 传递,只是一个字符串消息。鉴于 sayGreeting() 可能在多个组件中使用,具有完全相同的定义,是否可以将其提取到文件中(参见以下代码),然后根据需要以某种方式将其包含在每个组件中。这就像 Ruby 等编程语言中的包含模块(或 mixin?)模式。
export const sayGreeting = () => {
return this.props.greeting;
};
我可以通过从该文件导入 sayGreeting 并设置 MyComponent 的原型来做到这一点:
import { sayGreeting } from './someFile';
// ...
MyComponent.prototype.sayGreeting = sayGreeting;
但问题在于“this”关键字,因此不会定义 props。我尝试使用this.sayGreeting = this.sayGreeting.bind(this)在构造函数中绑定,但没有成功。
【问题讨论】:
-
你总是可以通过
props,比如<div>{this.sayGreeting(props)}</div>
标签: javascript class reactjs refactoring dry