Javascript 如何处理react redux connect函数中的REF
我有一个由react redux“connect()”函数包装的组件,我必须使用react中的Refs管理Javascript 如何处理react redux connect函数中的REF,javascript,reactjs,redux,react-redux,Javascript,Reactjs,Redux,React Redux,我有一个由react redux“connect()”函数包装的组件,我必须使用react中的Refs管理 我正在使用此版本的react/react-redux/redux: “反应”:“^16.13.1”, “react redux”:“^7.2.1”, “redux”:“^4.0.5” 我在谷歌上搜索了一整天,但我看到了一切可以帮助我的东西 使用钩子的人。。。好的,但在这个阶段我不想使用它们,因为我必须先研究它们 有人说“您可以在包装器组件上放置一个ref”。。。好吧,但在我8小时的谷歌搜索
我正在使用此版本的react/react-redux/redux:
“反应”:“^16.13.1”,
“react redux”:“^7.2.1”,
“redux”:“^4.0.5”
我在谷歌上搜索了一整天,但我看到了一切可以帮助我的东西
使用钩子的人。。。好的,但在这个阶段我不想使用它们,因为我必须先研究它们
有人说“您可以在包装器组件上放置一个ref”。。。好吧,但在我8小时的谷歌搜索中,我不知道怎么做
是否有人可以帮助我理解并告诉我如何编写正确的代码?
谢谢
我的组件的代码如下所示:
class EditorArea extends Component {
constructor(props) {
super(props)
this.textAreaRef = React.createRef();
}
render() {
const {
handleEditorChange,
handleTextSelection,
markdownText } = this.props;
return (
<Fragment>
<div id="editor-area">
<div id="text-area">
<textarea
id="editor"
ref={this.textAreaRef}
onChange={handleEditorChange}
onClick={() => handleTextSelection(this.textAreaRef)}
onSelect={() => handleTextSelection(this.textAreaRef)}
value={markdownText}
placeholder="Start here...">
</textarea>
</div>
</div>
</Fragment>
)
}
}
const madDispatch = dispatch => {
return {
handleEditorChange: (e) => dispatch(handleEditorChange(e)),
handleTextSelection: () => dispatch(handleTextSelection())
}
}
const mapState = state => {
const { editingStatus, markdownText } = state.changeMarkdownText;
return {
editingStatus,
markdownText,
}
}
export default connect(
mapState, madDispatch, null, { forwardRef: true }
)(EditorArea);
我认为您的问题可能在于
mapspatch
函数。您没有将ref作为参数传递,因此它总是分派未定义的
(空参数)。请尝试以下方法:
const madDispatch = dispatch => {
return {
handleEditorChange: (e) => dispatch(handleEditorChange(e)),
//pass a param here:
handleTextSelection: (textAreaRef) => dispatch(handleTextSelection(textAreaRef))
}
}
有什么问题?您是否试图在redux状态下存储html元素(您不应该也可能不能)?谢谢@HMR,我编辑了问题并添加了更多细节。谢谢您的回答,但这似乎不是解决方案。根据您的建议,错误仍然存在。我不知道怎么做,即使我没有在MapDispatch内的函数中声明参数,值仍然是传递的。嗯,奇怪。看看我制作的这个沙盒:当你的
handletexselection
没有作为分派道具传递时,它似乎工作得很好。这就是为什么我认为它与mapDispatch
功能相关。您能分享一下mapDispatch
是如何处理修复的吗?谢谢您的支持,是的。。。您是对的,问题与函数中缺少的参数有关。通过在沙箱中重写代码,我发现了其他问题并解决了它们。
const madDispatch = dispatch => {
return {
handleEditorChange: (e) => dispatch(handleEditorChange(e)),
//pass a param here:
handleTextSelection: (textAreaRef) => dispatch(handleTextSelection(textAreaRef))
}
}