【发布时间】:2020-09-09 17:51:14
【问题描述】:
我有一个由 react-redux "connect()" 函数包装的组件,我必须在 React 中使用 Refs 管理 <textarea>。
我正在使用这个版本的 react/react-redux/redux: “反应”:“^16.13.1”, "react-redux": "^7.2.1", "redux": "^4.0.5",
我整天都在谷歌上搜索,但我已经看到了所有可以帮助我的东西。
使用钩子的人... 好的,但现阶段我不想使用它们,因为我必须先研究它们
有人说“你可以在包装器组件上放一个引用”... 好的,但是在我 8 小时的 Google 搜索中,我不知道该怎么做? p>
是否有人可以帮助我理解并告诉我如何编写正确的代码? 谢谢
我的组件代码如下:
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 函数中访问 textarea DOM 对象的 selectionStart 和 selectionEnd 属性,但我得到了错误“TypeError:无法读取未定义的属性“当前””
这是我的动作创建函数:
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
}
}
【问题讨论】:
-
有什么问题?您是否尝试将 html 元素存储为 redux 状态(您不应该也可能不能)?
-
感谢@HMR,我编辑了问题,添加了更多细节。
标签: javascript reactjs redux react-redux