带有value的React textarea是只读的,但需要更新

React textarea with value is readonly but need to be updated

本文关键字:更新 value React textarea 带有 只读      更新时间:2023-09-26

我有一个文本区在我的React应用程序谁是充满了一个值。我希望这个文本区被更新和表单提交更新行在数据库中。

<textarea id="description" className="materialize-textarea" length="120" value={description} disabled={isDisabled}></textarea>

description变量用数据库中的值填充文本区域。该字段未禁用。

我试图附加一个onChange事件,它调度一个动作(redux)来改变文本区域的值,但它触发每个字母,它太慢了。

我如何创建一个文本区谁是由一个值填充,是可编辑的?

谢谢!

这个组件有两个textarea。道具和状态之间存在一种受控关系。这是输入的关键。注意componentWillReceiveProps。

    import React, {Component} from 'react';
    import Actions from '../../flux/Actions';
    let CurrentSnipDivSty = {
        height: 'calc(((100% - 40px) * .4) - 3px)',
        minHeight: '9.5em',
        width: '100%'
    };
    let CurrentSnipTextAreaSty = {
        backgroundColor: '#213919',
        border: '1px solid #314929',
        color: '#afac87',
        fontSize: '1em',
        height: 'calc(50% - 20px)',
        overflowY: 'auto',
        padding: '5px',
        width: 'calc(100% - 12px)'
    };
    class SnipsDetailRender extends Component {
        render() {
            let snip = this.state.snip.snip;
            let comment = this.state.snip.comment;
            return (
                <div id='CurrentSnipDivSty' style={CurrentSnipDivSty}>
                    <textarea
                        value={snip}
                        onChange={this.handleSnipChange}
                        style={CurrentSnipTextAreaSty} />
                    <textarea
                        value={comment}
                        onChange={this.handleCommentChange}
                        style={CurrentSnipTextAreaSty} />
                </div>
            );
        }
    }
    export default class SnipsDetail extends SnipsDetailRender {
        constructor() {
          super();
            this.state = { snip: {snip: '', comment: ''} };
        }
        componentWillReceiveProps = (nextProps) => {
            if ((nextProps.data.snip != this.state.snip.snip) || (nextProps.data.comment != this.state.snip.comment))
             this.setState({snip: nextProps.data});
        }
        handleSnipChange = (ev) => {
            let newSnip = {snip: ev.target.value, comment: this.state.snip.comment};
            this.setState({snip: newSnip});
            Actions.saveSnipEdit(newSnip);
        }
        handleCommentChange = (ev) => {
            let newSnip = {snip: this.state.snip.snip, comment: ev.target.value};
            this.setState({snip: newSnip});
            Actions.saveSnipEdit(newSnip);
        }
    }

如果您发现使用onChange事件太慢,您可以简单地使用refs从提交处理程序中的DOM中读取。下面是一个示例:

https://facebook.github.io/react/docs/tutorial.html adding-new-comments

由于您正在使用redux,您可能可以将许多功能导出到操作创建器。