【发布时间】:2016-06-06 00:51:45
【问题描述】:
我正在尝试在 React ES6 类扩展的 React.Component 中添加一个公共函数。但是,我没有尝试使该功能对其他组件公开可用。
欢迎任何提示。
以下是我尝试过的一些示例:
import React, { PropTypes } from 'react'
import ChildComponent from './ChildComponent'
export class ArticleModal extends React.Component<void, Props, void> {
static propTypes = {
};
constructor (props) {
super(props)
}
static privateMethod () {
// This doesn't work
}
set privateMethod2 () {
// This doesn't work either
}
privateMethod3 () {
// ...and neither does this.
}
render () {
return (
<p>Some content</p>
)
}
}
const mapStateToProps = (state) => ({
})
export default connect((mapStateToProps), {
})(ArticleModal)
【问题讨论】:
-
你能看到正确的
.render()吗? -
是的,它渲染得很好,只是当我尝试调用任何私有方法时,我得到了错误。
Uncaught TypeError: this._component.privateMethod is not a function我绑定了this._component,看起来不错,我从 React 和 Redux 获取方法,我看到它是存储在this._component变量中的正确组件。 -
.privateMethod3应该具有与.render相同的“可达性”;我不明白只有一个是如何工作的...... -
啊,现在我明白你的意思了。不,我看不到渲染方法,但组件确实渲染了。我认为它确实帮助我解决了这个问题。答案是从组件中访问“renderedElement”,在那里我找到了一个“类型”对象,该对象引用了具有可用方法的类。这确实感觉像是一个糟糕的解决方案,就像我只是访问类而不是实例一样。
-
你想达到什么目的? React 组件并非旨在将方法暴露给应用程序的其他部分;那不是他们的目的。只有组件本身应该调用它自己的方法。如果需要由另一个组件调用某些内容,则该函数将作为道具传递。但是不应该有“公共”方法的感觉。
标签: javascript reactjs components ecmascript-6