3

我的 React 应用程序中有一个文本区域,其中填充了一个值。我希望更新此文本区域并提交表单以更新数据库中的行。

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

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

我试图附加一个 onChange 事件,该事件调度一个动作(redux)来更改 textarea 的值,但它会为每个字母触发,而且速度太慢。

如何创建一个由值填充且可编辑的文本区域?

谢谢!

4

2 回答 2

3

这是一个有两个文本区域的组件。props 和 state 之间存在受控关系。这是输入的关键。注意 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);
        }
    }
于 2015-10-19T21:00:30.950 回答
1

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

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

由于您使用的是 redux,您可能可以将很多功能导出到动作创建者。

于 2015-10-27T02:59:00.217 回答