如何使用react-js将复选框值与以动态形式输入的文本绑定?

时间:2019-03-08 20:10:25

标签: javascript reactjs dynamic-forms

我在react-js中有一个动态表单,我的一些元素是复选框/单选框,其中的一个绑定了文本输入。
例如,问题是: 什么是你最喜欢的颜色?

答案是:

 - red
 - blue
 - green
 - OTHER

和其他答案的前面都有文本输入,以便用户在其中键入自己的自定义答案。 如何将复选框/收音机绑定到相关的输入文本并获取其值? form

2 个答案:

答案 0 :(得分:0)

如果您使用更新版本的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

答案 1 :(得分:0)

我使用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>
    );
  }
}

See working example here