反应选择onChange空事件

时间:2019-06-21 14:01:15

标签: reactjs typescript

我有以下React组件,该组件使用select标签,该标签的状态由该组件管理:

<main id='homescreen-container'>
                {/* TODO: Add maxLength after deciding on a font size */}
                <textarea readOnly id="recorded-text-view" value={this.state.displayedContent}></textarea>
                <button className="button" onClick={this.toggleRecording}>{!this.state.recording ? "Înregistrează" : "Stop"}</button>
                <h5>Paragraful curent</h5>
                    <select id="current-paragraph" value={this.state.workingPage.WorkingParagraphIndex} onChange={(event) => this.changeCurrentParagraph(event)}>
                        {this.state.workingPage.Paragraph.map((val, index) => (
                            <option key={index} value={index + 1}>{index + 1}</option>
                        ))}
                    </select>
                <button className="button" onClick={this.createNewParagraph}>Adaugă un paragraf</button>
                <button className="button" onClick={this.deleteCurrentParagraph}>Șterge paragraful curent</button>
                <button className="button" onClick={this.saveFile}>Salvează</button>
            </main>

我的问题是,当我尝试处理onChange事件时,传递给处理程序的事件具有null作为目标属性。这是我的处理程序:

changeCurrentParagraph = (event: any) => {
        console.log(event);
        this.setState((prev: HomescreenState) => ({
            workingPage: prev.workingPage.changeWorkingParagraph(event.target.value)
        }))
    }

这不起作用,并引发以下错误:TypeError: Cannot read property 'value' of null。知道可能是什么问题吗?预先感谢!

1 个答案:

答案 0 :(得分:1)

您的问题可能是由于您试图在setState中设置值的方式引起的。尝试更改代码以遵循以下模式:

changeCurrentParagraph = (event: any) => {
        console.log(event);
        const myVal = this.state.workingPage.changeWorkingParagraph(event.target.value) //assuming you are returning a value from this
        this.setState((prev: HomescreenState) => ({
            workingPage: myVal
        }))
    }