簡體   English   中英

如何使用react-js將復選框值與以動態形式輸入的文本綁定?

[英]How to bind checkbox value with text input in dynamic form with react-js?

我在react-js中有一個動態表單,我的一些元素是復選框/單選框,其中一個具有綁定到其上的文本輸入。
例如,問題是:您最喜歡的顏色是什么?

答案是:

 - red
 - blue
 - green
 - OTHER

和OTHER答案前面有一個文本輸入,供用戶在其中鍵入自己的自定義答案。 如何將復選框/收音機綁定到相關的輸入文本並獲取其值? 形成

如果您使用較新版本的React,請嘗試使用狀態掛鈎。 遵循以下原則

import React, { useState } from 'react';

function Example() {
  const [color, setColor] = useState('');

  return (
    <div>
    <select value={color} 
          onChange={(e) => setColor(value)}>
      { ['red', 'blue', 'green', 'OTHER'].map((c) => <option key={c} value={c}>{c}</option>)}
    </select>
    {color === 'OTHER' && <input type="text"></input>}
    </div>
  );
}

https://reactjs.org/docs/hooks-state.html

使用Material UI,我使用了類似的解決方案來添加可填充的“其他”復選框:

import React from "react";
import ReactDOM from "react-dom";
import FormGroup from "@material-ui/core/FormGroup";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import Checkbox from "@material-ui/core/Checkbox";
import TextField from "@material-ui/core/TextField";

import "./styles.css";

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      options: ["red", "blue", "green", "other"],
      filterOptions: ["red", "blue", "green"],
      checkedValues: [],
      otherValue: "other"
    };
  }

  handleOther = () => event => {
    let value = event.target.value;
    this.setState({
      otherValue: value
    });
  };

  handleSaveOther = () => event => {
    let newCheckedValues = [...this.state.checkedValues]; // make a separate copy of the array
    let intersection = newCheckedValues.filter(x =>
      this.state.filterOptions.includes(x)
    );
    let allValues = [...intersection, this.state.otherValue];

    if (this.state.other) {
      this.setState({
        checkedValues: allValues
      });
    }
  };

  handleCheck = option => event => {
    let value = event.target.value;
    let checked = event.target.checked;
    let newCheckedValues = [...this.state.checkedValues]; // make a separate copy of the array
    let index = newCheckedValues.indexOf(value);
    if (index !== -1) {
      newCheckedValues.splice(index, 1);
      this.setState({
        checkedValues: newCheckedValues,
        [option]: checked
      });
    } else {
      this.setState({
        checkedValues: [...this.state.checkedValues, value],
        [option]: checked
      });
    }
  };

  render() {
    const { options, checkedValues, otherValue } = this.state;
    console.log(checkedValues);
    return (
      <div className="App">
        <div style={{ width: "50%", margin: "0 auto" }}>
          <FormGroup>
            {options.map((option, i) => {
              return (
                <FormControlLabel
                  control={
                    <Checkbox
                      onChange={this.handleCheck(option)}
                      value={option === "other" ? otherValue : option}
                      color={"primary"}
                    />
                  }
                  label={
                    option === "other" ? (
                      <TextField
                        id={"other"}
                        name={"other"}
                        value={this.state.otherValue}
                        fullWidth
                        onChange={this.handleOther()}
                        onBlur={this.handleSaveOther()}
                      />
                    ) : (
                      option
                    )
                  }
                />
              );
            })}
          </FormGroup>
        </div>
      </div>
    );
  }
}

在這里查看工作示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM