如何将对象数组从输入框传递到JavaScript中的单独数组

时间:2019-02-16 07:41:39

标签: javascript reactjs

我正在一个React项目中,我有一个文本输入,它将输入n次输入值。屏幕看起来像这样:

image1

单击下一步后,该值将在下一页提交,我们可以回来在下面的屏幕快照所示的页面的文本框中输入更多值。对于我在中输入的每个值,将有一个对应的单选按钮值。因此,我在状态下创建了一个数组,该数组将具有文本框的值。

this.state = { 
    buildingNames: [],
    selectedOptions: ''
}

selectedOptions状态采用单选按钮值。因此,目前每当在texbox中添加新值时,我都会将其推送到buildingNames状态。但是我无法获取如何为每个buildingName获取相应的radioButton值并将其作为对象数组推送。 目前,我正在将文本框的值推入数组,例如:

const tempState = [...this.state.buildingNames];
tempState.push(inputData.value);
this.setState({buildingNames: tempState });

其中inputData.value是在文本框中输入的值。

所以我的最终数组应该像:

buildingDetails:[
  {
    buildingName:'abc'
    radioButtonValue:'1'
  },
  {
    buildingName:'def'
    radioButtonValue:'2'
  },
  {
    buildingName:'ghi'
    radioButtonValue:'3'
  },
  // so on
] 

我无法理解如何获取对应建筑物的单选按钮的值。所以,我该如何进行。有人可以引导我吗?

1 个答案:

答案 0 :(得分:1)

方法1

您可以使buildingDetails为对象(将具有buildingNameradioButtonValue键),并添加另一个状态pageNopageNo可用作将数据保存在buildingDetails中的索引。因此buildingDetails[0].buildingName将存储第一页buildingName的输入值。依此类推。

这里是一个示例,我在必要时添加了评论:

class Reservation extends React.Component {
  numberOfPages = 10 // total number of pages

  constructor(props) {
    super(props)
    this.state = {
      pageNo: 0, // which page we are currently on, 0 based
      buildingDetails: {}, // this is an object which should be indexed with `pageNo`
    }
  }

  handleInputChange = event => {
    const target = event.target
    const value = target.type === 'checkbox' ? target.checked : target.value
    const name = target.name

    // save the data to the corresponding `pageNo` index of buildingDetails
    this.setState(prevState => ({
      buildingDetails: {
        ...prevState.buildingDetails,
        [prevState.pageNo]: {
          ...prevState.buildingDetails[prevState.pageNo],
          [name]: value,
        },
      },
    }))
  }

  handlePrevClick = e => {
    // TODO: implement your own logic so that it never goes past page 0
    e.preventDefault()
    this.setState(prevState => ({
      pageNo: prevState.pageNo - 1,
    }))
  }
  handleNextClick = e => {
    // TODO: implement your own logic so that it never goes beyond last page
    e.preventDefault()
    this.setState(prevState => ({
      pageNo: prevState.pageNo + 1,
    }))
  }

  render() {
    return (
      <form>
        <label>
          Building Name:
          <input
            name="buildingName"
            value={
              this.state.buildingDetails[this.state.pageNo]
                ? this.state.buildingDetails[this.state.pageNo].buildingName
                : ''
            }
            onChange={this.handleInputChange}
          />
        </label>
        <br />
        <div>
          Dummy Gender:
          <input
            type="radio"
            name="radioButtonValue"
            value="male"
            checked={
              this.state.buildingDetails[this.state.pageNo]
                ? this.state.buildingDetails[this.state.pageNo]
                    .radioButtonValue === 'male'
                : false
            }
            onChange={this.handleInputChange}
          />{' '}
          Male
          <input
            type="radio"
            name="radioButtonValue"
            value="female"
            checked={
              this.state.buildingDetails[this.state.pageNo]
                ? this.state.buildingDetails[this.state.pageNo]
                    .radioButtonValue === 'female'
                : false
            }
            onChange={this.handleInputChange}
          />{' '}
          Female
          <br />
        </div>

        <button onClick={this.handlePrevClick}>Prev</button>
        <button onClick={this.handleNextClick}>Next</button>
        <br />
        <code>{JSON.stringify(this.state)}</code>
      </form>
    )
  }
}

function App() {
  return (
    <div className="App">
      <Reservation />
    </div>
  )
}

const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

方法2

buildDetails将是一个数组,您最初会用占位符对象填充它。使用pageNo为数组建立索引,方法几乎与以前相同。在这里,您将当前数组映射到一个新数组,但修改在pageNo处索引的对象:

class Reservation extends React.Component {
  numberOfPages = 10; // total number of pages

  constructor(props) {
    super(props);
    this.state = {
      pageNo: 0, // which page we are currently on, 0 based
      buildingDetails: new Array(this.numberOfPages).fill({
        buildingName: "",
        radioButtonValue: ""
      }) // this is an array which should be indexed with `pageNo`
    };
  }

  handleInputChange = event => {
    const target = event.target;
    const value = target.type === "checkbox" ? target.checked : target.value;
    const name = target.name;

    // save the data to the corresponding `pageNo` index of buildingDetails
    this.setState(prevState => ({
      buildingDetails: prevState.buildingDetails.map((detail, index) => {
        if (index !== prevState.pageNo) {
          // This isn't the item we care about - keep it as-is
          return detail;
        }

        // Otherwise, this is the one we want - return an updated value
        return {
          ...detail,
          [name]: value
        };
      })
    }));
  };

  handlePrevClick = e => {
    // TODO: implement your own logic so that it never goes past page 0
    e.preventDefault();
    if (this.state.pageNo === 0) return;
    this.setState(prevState => ({
      pageNo: prevState.pageNo - 1
    }));
  };
  handleNextClick = e => {
    // TODO: implement your own logic so that it never goes beyond last page
    e.preventDefault();
    if (this.state.pageNo === this.numberOfPages - 1) return;
    this.setState(prevState => ({
      pageNo: prevState.pageNo + 1
    }));
  };

  render() {
    return (
      <form>
        <label>
          Building Name:
          <input
            name="buildingName"
            value={this.state.buildingDetails[this.state.pageNo].buildingName}
            onChange={this.handleInputChange}
          />
        </label>
        <br />
        <div>
          Dummy Gender:
          <input
            type="radio"
            name="radioButtonValue"
            value="male"
            checked={
              this.state.buildingDetails[this.state.pageNo].radioButtonValue ===
              "male"
            }
            onChange={this.handleInputChange}
          />{" "}
          Male
          <input
            type="radio"
            name="radioButtonValue"
            value="female"
            checked={
              this.state.buildingDetails[this.state.pageNo].radioButtonValue ===
              "female"
            }
            onChange={this.handleInputChange}
          />{" "}
          Female
          <br />
        </div>

        <button onClick={this.handlePrevClick}>Prev</button>
        <button onClick={this.handleNextClick}>Next</button>
        <br />
        <code>{JSON.stringify(this.state)}</code>
      </form>
    );
  }
}

function App() {
  return (
    <div className="App">
      <Reservation />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

希望有帮助。