如何在React中将对象附加到组件主体?

时间:2019-07-13 14:20:15

标签: javascript reactjs jsx

我正在尝试在此React组件上设置一些功能,以便用户可以在用户可以输入文本的页面上添加和删除空的单选按钮选项。我唯一遇到的问题是,我对React还是比较陌生的,而不是100%如何做到这一点。

import React, { Component } from 'react';

class TextRadio extends Component {
    constructor() {
        super();

        state = {
            textValue: ""
        }

    };

    handleInputChange = event => {
        const value = event.target.value;
        const name = event.target.name;

        this.setState({
            [name]: value
        });
    }

    addBox = () => {

    }

    removeBox = () => {

    }

    render() {
        return(
            <div>
                <div className="form-check">
                    <input className="form-check-input" type="radio" id="" name="" value="" />
                    <label className="form-check-label" for="">
                        <input class="form-control" type="text" placeholder="" />
                    </label>
                </div>
                <div className="form-check">
                    <input className="form-check-input" type="radio" id="option" name="option" value="option" />
                    <label className="form-check-label" for="option">
                        <input class="form-control" type="text" placeholder="" />
                    </label>
                </div>
                <div className="form-check">
                    <input className="form-check-input" type="radio" id="option" name="option" value="option" />
                    <label className="form-check-label" for="option">
                        <input class="form-control" type="text" placeholder="" />
                    </label>
                </div>
                <button type="button" className="btn btn-primary" onClick={this.addBox}>
                    Add Option
                </button>
                <button type="button" className="btn btn-danger" onClick={this.removeBox}>
                    Remove Option
                </button>
            </div>
        );
    }
}

export default TextRadio;

我希望发生的结果是拥有它,以便组件可以根据用户按下的按钮从页面添加和删除单选按钮选项

3 个答案:

答案 0 :(得分:0)

我一直在研究您的想法,并对代码进行了一些更改,只是为了向您展示一个示例,说明如何动态创建新组件并将其存储在应用程序状态,然后根据用户的操作向用户呈现。 / p>

我只为表单UI创建了新组件:选项,输入字段和删除按钮。如果用户单击“添加选项”,则组件的新项目将添加到应用程序状态,然后呈现出来。删除按钮用于从状态中删除项目。

class TextRadio extends Component {
  state = {
    optionInputs: []
  };

  addBox = () => {
    const optionInputsUpdated = [
      ...this.state.optionInputs,
      <OptionInput id={uuid.v4()} remove={this.removeBox} />
    ];
    this.setState({ optionInputs: optionInputsUpdated });
  };

  removeBox = id => {
    const optionInputsUpdated = this.state.optionInputs.filter(
      item => item.props.id !== id
    );
    this.setState({ optionInputs: optionInputsUpdated });
  };

  render() {
    return (
      <div>
        {this.state.optionInputs.map((optionInput, idx) => {
          return (
            <div key={idx} test="123">
              {optionInput}
            </div>
          );
        })}
        <button type="button" className="btn btn-primary" onClick={this.addBox}>
          Add Option
        </button>
      </div>
    );
  }
}

const OptionInput = props => {
  return (
    <div className="form-check">
      <input
        className="form-check-input"
        type="radio"
        id=""
        name="radio"
        value=""
      />
      <label className="form-check-label" for="">
        <input className="form-control" type="text" placeholder="" />
      </label>{" "}
      <button
        type="button"
        className="btn btn-danger"
        onClick={() => props.remove(props.id)}
      >
        Remove Option
      </button>
    </div>
  );
};

希望这可以使您更好地了解如何实现目标。

如果您需要其他帮助,只需在此答案下发表评论,我将更新演示以帮助您。

这是我根据您的代码创建的DEMO:https://codesandbox.io/s/nice-ganguly-s4wls

答案 1 :(得分:0)

首先,您必须初始化一个空数组状态

this.state={
  radioButtons : [{input:''}]
}

然后在return语句中,您必须遍历radioButtons数组并显示带有输入的单选按钮

{
  this.state.radioButtons.map(item => (
    <div className="form-check">
        <input className="form-check-input" type="radio" id="option" name="option" value="option" />
        <label className="form-check-label" for="option">
        <input class="form-control" type="text" placeholder="" />
        </label>
    </div>
  ))
}

然后在您的addBox函数中,在每次单击时都添加一个对象

      addBox = () => {
        this.setState({radioButtons:[...this.state.radioButtons, {input:''}]})
}

删除单选按钮对象的功能

  removeBox = () => {
    let radioArray = this.state.radioButtons
    radioArray.pop()
    this.setState({radioButtons:radioArray})
  }

最终代码如下:

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends React.Component{
  constructor(props){
    super(props);
    this.state={
      radioButtons :[{input:''}]
    }
  }

  addBox = () => {
    this.setState({radioButtons:[...this.state.radioButtons, {input:''}]})

  }
  removeBox = () => {
    let radioArray = this.state.radioButtons
    radioArray.pop()
    this.setState({radioButtons:radioArray})
  }

  render(){
    return(
      <div>
              {
      this.state.radioButtons.map(item => (
        <div className="form-check">
            <input className="form-check-input" type="radio" id="option" name="option" value="option" />
            <label className="form-check-label" for="option">
            <input class="form-control" type="text" placeholder="" />
            </label>
        </div>
      ))
    }
               <button type="button" className="btn btn-primary" onClick={this.addBox}>
                    Add Option
                </button>
                <button type="button" className="btn btn-danger" onClick={this.removeBox}>
                    Remove Option
                </button>

      </div>
    )
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

codepen Example

答案 2 :(得分:0)

我仅完成了您的addBoxRemoveBox函数,希望对您有所帮助

import React, { Component } from "react";

class TextRadio extends Component {
  constructor() {
    super();

    this.state = {
      radioButtons: []
    };
  }

  handleInputChange = event => {
    const value = event.target.value;
    const name = event.target.name;
  };

  addBox = () => {
    this.setState(prevstate => {
      let radioButtons = prevstate.radioButtons;
      if (radioButtons.length === 0) {
        radioButtons.push({
          id: 1,
          name: "radiobutton",
          value: "test"
        });
        return {
          radioButtons: radioButtons
        };
      } else {
        radioButtons.push({
          id: radioButtons[radioButtons.length - 1].id + 1,
          name: "raiodButton_" + (radioButtons[radioButtons.length - 1].id + 1),
          value: radioButtons[radioButtons.length - 1].value
        });
        return {
          radioButtons: radioButtons
        };
      }
    });
  };

  removeBox = () => {
    this.setState(prevstate => {
      let radioButtons = prevstate.radioButtons;
      if (radioButtons.length !== 0) {
        radioButtons.pop(radioButtons[radioButtons.length - 1]);
        return {
          radioButtons: radioButtons
        };
      } else {
        return { radioButtons: radioButtons };
      }
    });
  };

  render() {
    return (
      <div>
        <div className="form-check">
          {this.state.radioButtons.map(radiobutton => {
            return (
              <div>
                <input
                  className="form-check-input"
                  type="radio"
                  id={radiobutton.id}
                  name={radiobutton.name}
                  value={radiobutton.value}
                />
                <label className="form-check-label" for="">
                  <input class="form-control" type="text" placeholder="" />
                </label>
              </div>
            );
          })}
        </div>
        <button type="button" className="btn btn-primary" onClick={this.addBox}>
          Add Option
        </button>
        <button
          type="button"
          className="btn btn-danger"
          onClick={this.removeBox}
        >
          Remove Option
        </button>
      </div>
    );
  }
}

export default TextRadio;

https://codesandbox.io/embed/confident-browser-tmojp