反应。将数据从文本区域传输到数组 JSON

React. Transferring data from textarea to array JSON

我刚开始使用 React 和 JSON,需要一些帮助。有一个 textarea 字段,用户可以在其中输入一些数据。如何将输入的文本作为数组按行读取到请求的 JSON 变量中?如有任何帮助,我们将不胜感激。

我想要的结果是

     {
        id: 3,
        name: 'Monika',
        birthDay: '1999/01/01',
        countryDTO: 'USA',
        films: [
                  'Leon:The Professional',
                  'Star wars',
                  'Django Unchained',
               ],
    } ```

我的代码:

    import React from 'react';
    import { Form, FormGroup, Label } from 'reactstrap';
    import '../app.css';

    export class EditActor extends React.Component {
    state = {
        id: '',
        name: '',
        birthDay: '',
        countryDTO: '',
        films: [],
    }

    componentDidMount() {
        if (this.props.actor) {
            const { name, birthDay, countryDTO, films } = this.props.actor
            this.setState({ name, birthDay, countryDTO, films });
        }
    }

    submitNew = e => {
        alert("Actor added"),
            e.preventDefault();
        fetch('api/Actors', {
            method: 'post',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                name: this.state.name,
                birthDay: this.state.birthDay,
                countryDTO: {
                    title: this.state.countryDTO
                },
                films: [{ title: this.state.films }]
            })
        })
            .then(() => {
                this.props.toggle();
            })
            .catch(err => console.log(err));

        this.setState({
            id: '',
            name: '',
            birthDay: '',
            countryDTO: '',
            films: ''
        });
    }

    onChange = e => {
        this.setState({ [e.target.name]: e.target.value })
    }

    render() {
        return <div>
            <table>
                    <tr>
                        <td colspan="2">   
                            <h3> <b>Add actor</b></h3>

                    <FormGroup>
                    <Label for="id">Id:  </Label>
                                <input type="text" name="id" onChange={this.onChange} value={this.state.id} /><p />

                    <Label for="name">Name:</Label>
                                <input type="text" name="name" onChange={this.onChange} value={this.state.name} /><p />

                    <Label for="birthDay">Birth day:</Label>
                    <input type="text" name="birthDay" onChange={this.onChange} value={this.state.birthDay} placeholder="1990/12/31" /><p />

                    <Label for="country">Country:</Label>
                                <input type="text" name="countryDTO" onChange={this.onChange} value={this.state.countryDTO} /><p />

                    <Label for="Films">Films:</Label>
                    <textarea name="films" value={this.state.films} onChange={this.onChange} /><p />
                    </FormGroup>

                        </td>
                    </tr>
                    <tr>
                        <td>

                <Form onSubmit={this.submitNew}>
                            <button class="editButtn">Enter</button>
                </Form>
                        </td>

                    </tr>
            </table >
        </div>;
    }
}

export default EditActor;

更改 textarea() 标签 至

<textarea name="films" value={this.state.films} onChange={this.onChange} >{this.state.films}</textarea>

如果您更改以下代码,它将自动运行。

状态声明

 this.state = {
      name: 'React',
      films:["Palash","Kanti"]
    };

onechange函数的变化

onChange = e => {
  console.log("values: ", e.target.value)
    this.setState({ [e.target.name]: e.target.value.split(",") })
}

文本区域发生变化

  <textarea name="films" value={this.state.films.map(r=>r).join(",")} onChange={this.onChange} />

代码在这里: https://stackblitz.com/edit/react-3hrkme

您可以使用 split() :

films: {this.state.films.split(",")}

您必须关闭 textarea 标签 并且以下代码是:

<textarea name="films" value={this.state.films} onChange={this.onChange} >{this.state.films}</textarea>

我对您的问题的理解是,您希望将文本区域中的每一行动态添加为电影数组中的条目。这可以通过以下方式实现:

import React, { Component } from "react";

export default class textAreaRowsInState extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentTextareaValue: "",
      films: []
    };
  }

  handleChange = e => {
    const { films } = this.state;
    const text = e.target.value;
    if (e.key === "Enter") {
      // Get last line of textarea and push into films array
      const lastEl = text.split("\n").slice(-1)[0];
      films.push(lastEl);
      this.setState({ films });
    } else {
      this.setState({ currentTextareaValue: text });
    }
  };

  render() {
    const { currentTextareaValue } = this.state;
    return (
      <textarea
        defaultValue={currentTextareaValue}
        onKeyPress={this.handleChange}
      />
    );
  }
}

请记住,此方法并不完美。例如,如果您在文本区域末尾以外的任何地方添加新行,它将失败。您可以在此处查看此解决方案的实际应用:

https://codesandbox.io/s/infallible-cdn-135du?fontsize=14&hidenavigation=1&theme=dark