如何从另一个类创建对象并将其推入状态数组?

时间:2020-01-22 23:27:13

标签: javascript html arrays reactjs

我目前正在开发一个React应用程序,其中有两个类-我们将其称为App类和Container类。基本上,App类具有一个状态数组,并且我想在此数组中包含许多Container对象。

class Container extends React.Component{
    render(){
       return(
          <img src= {this.props.url} />
       );
    }
}



class App extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            url: ""
            data: []
        }
    }


    handleSubmit(event){
        event.preventDefault();

        //I WANT TO BE ABLE TO MAKE A NEW CONTAINER, AND PASS THE URL AS PROPS.
        // THEN, I WANT TO ADD THAT CONTAINER TO THE ARRAY.     

        this.setState({
            data: url = this.state.url, id = 'a'
        });
    }


    render(){
        return (
           <form onSubmit={this.handleSubmit}>
                <label htmlFor="url">url:</label>
                    <input
                        type = "text"
                        name = "url"
                        value = {this.state.url}
                        onChange = {this.handleChange}
                    />
           </form>

        )
    }
}

在上述功能handleSubmit()中,我想向数组添加一个包含props URL的新容器。我该怎么办?

1 个答案:

答案 0 :(得分:1)

  1. 不要改变国家
  2. 您只需要url处于状态,而不是整个容器
  3. 使用setState修改状态
  4. 考虑使用传播运算符(...)进行串联
  5. 我在您的代码中看不到handleChange
    class Container extends React.Component {
      render() {
        return <img src={this.props.url} />;
      }
    }

    class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          url: "",
          containers: []
        };
      }

      handleChange = e => {
        this.setState({
          url: e.target.value
        });
      };

      handleSubmit = event => {
        event.preventDefault();
        if (this.state.url) {
          this.setState({
            containers: [...this.state.containers, this.state.url],
            url: ""
          });
        }
      };

      render() {
        const { url, containers } = this.state;
        return (
          <div>
            <form onSubmit={this.handleSubmit}>
              <label htmlFor="url">url:</label>
              <input
                type="text"
                name="url"
                value={url}
                onChange={this.handleChange}
              />
              <button>submit</button>
            </form>

            <h2>Containers:</h2>
            <div>
              {!containers.length && <i>no urls added</i>}
              {containers.map((_url, i) => (
                <Container key={i} url={_url} />
              ))}
            </div>
          </div>
        );
      }
    }

    render(<App />, document.getElementById("root"));

工作示例: https://stackblitz.com/edit/react-g72uej