【问题标题】:React - form - unable to update/edit value in input/textarea - writing disableReact - 表单 - 无法更新/编辑输入/文本区域中的值 - 写入禁用
【发布时间】:2021-02-20 13:30:43
【问题描述】:

代码如下:

import React from 'react';

class EditEntry extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            entry: '',
            description: '',
            item: [],
            error: null
        };

        this.handleChangeEntry = this.handleChangeEntry.bind(this);
        this.handleChangeDescription = this.handleChangeDescription.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    componentDidMount() {
        const { match: { params } } = this.props;
        const { id } = params;
        fetch(`/api/entries/${id}`, {
            method: 'GET'
        })
            .then(response => response.json())
            .then(
                data => {
                    this.setState({
                        item: data
                    });
                },
                error => {
                    this.setState({
                        error
                    });
                });
    }

    handleChangeEntry(e) {
        this.setState({ entry: e.target.value });
    }

    handleChangeDescription(e) {
        this.setState({ description: e.target.value });
    }

    handleSubmit(e) {
        e.preventDefault();

        const { entry, description } = this.state;
        const { match: { params } } = this.props;
        const { id } = params;

        fetch(`/api/entries/${id}`, {
            method: 'PUT',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(entry, description)
        })
            .then(response => {
                if (response.ok) {
                    window.location.assign("/");
                } else {
                    throw new Error('No response.');
                }
            },
                error => {
                    this.setState({
                        error
                    });
                });
    }

    render() {

        const { item } = this.state;

        const itemEditForm = item.map(i => {
            return <div key={i.id}>
                <form onSubmit={this.handleSubmit}>
                    <div className="form-group">
                        <label htmlFor="entry">Entry</label>
                        <input
                            id="entry"
                            name="entry"
                            type="text"
                            className="form-control"
                            required
                            value={i.entry}
                            onChange={this.handleChangeEntry} />
                    </div>
                    <div className="form-group">
                        <label htmlFor="description">Description</label>
                        <textarea
                            id="description"
                            name="description"
                            type="text"
                            className="form-control"
                            required
                            rows="5"
                            value={i.description}
                            onChange={this.handleChangeDescription} />
                    </div>
                    <button type="submit" className="btn btn-secondary btn-sm mb-sm-2">Submit</button>
                </form>
            </div>
        });

        return (
            <div>
                {itemEditForm}
            </div>
        );
    }
}

export default EditEntry;

我无法编辑包含在的数据:

<input id="entry" (...) />
<textarea id="description" (...) />

有数据,有光标,但这些字段无法编辑。

我从数据库 (componentDidMount()) 中获取一个包含一个对象的数组。我知道还有另一种方法可以访问对象中包含的数据。但是在这个项目中这种方式是行不通的。虽然在我的另一个项目中它有效。奇怪。

【问题讨论】:

    标签: javascript reactjs forms edit disable


    【解决方案1】:

    您正在 onChange 处理程序方法中设置“条目”和“描述”属性。但在输入的 value 属性中使用 i.entryi.description。请尝试更改它,也许如果您在项目数组中有多个项目,您可以尝试像下面这样来处理状态。

    组件:

    <input
                id="name"
                name="name"
                type="text"
                className="form-control"
                required
                value={i.name}
                onChange={(e) => this.handleChangeName(e, i.id)}
              />
    

    JS:

    handleChangeName(e, id) {
    console.log(e.target.value);
    const newState = {
      item: this.state.item.map((x) =>
        x.id != id ? x : { id: id, name: e.target.value }
      )
    };
    this.setState(newState);
    

    }

    另外,请在CodeSandbox Link上找到一个基于您的代码的工作示例

    谢谢。

    【讨论】:

    • 它几乎可以工作。我的意思是它有效,但仅适用于具有一个输入的表单。使用两个输入,只有一个值被传递给状态(加上 id)。此外,不受控制的组件存在问题(警告:组件正在将受控输入更改为不受控制...)。我必须在代码中添加和更改:this.entry = React.createRef();defaultValue={i.entry}ref={this.entry}“描述”也是如此。感谢沙盒代码 - 它有很大帮助。
    • 哦,好的。我再次尝试了沙箱中的 2 个输入字段,并通过一些小的调整成功地传递了值。在不受控制的表单的情况下可能会出现问题,但由于问题中没有提到这一点,我尝试用最少的代码复制您的问题。很高兴它有帮助。如果您认为答案有助于解决查询,请您将答案标记为已接受(或至少表示赞赏)谢谢。
    • 是的!现在一切正常!非常感谢你!就这么简单。我觉得很尴尬:)
    猜你喜欢
    • 2017-03-20
    • 2011-09-04
    • 1970-01-01
    • 1970-01-01
    • 2018-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多