簡體   English   中英

如何處理 Refs in react-redux connect function

[英]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 的selectionStartselectionEnd屬性,但我收到錯誤“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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM