[英]Understanding the syntax of connect() function in react-redux
[英]How to handle with Refs in react-redux connect function
我有一个由 react-redux“connect()”function 包装的组件,我必须在 React 中使用 Refs 管理<textarea>
。
我正在使用这个版本的 react/react-redux/redux: "react": "^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);
编辑:我忘了提及我的需求和问题:我需要在我的 action-creator function 中访问textarea
DOM object 的selectionStart和selectionEnd属性,但我收到错误“TypeError:无法读取未定义的属性‘current’”
这是我的动作创作者 function:
export const handleTextSelection = (text) => {
let newTextSelection = {};
let startSelection = text.current.selectionStart;
let endSelection = text.current.selectionEnd;
newTextSelection.startSelection = startSelection;
newTextSelection.endSelection = endSelection;
return {
type: MARKDOWN_TEXT_SELECTION,
payload: newTextSelection
}
}
我认为您的问题可能出在mapDispatch
function 上。您没有将 ref 作为参数传递,因此它总是调度undefined
的(空参数)。 试试这个:
const madDispatch = dispatch => {
return {
handleEditorChange: (e) => dispatch(handleEditorChange(e)),
//pass a param here:
handleTextSelection: (textAreaRef) => dispatch(handleTextSelection(textAreaRef))
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.