简体   繁体   English

如何动态改变输入的值?

[英]How to change the value of input dynamically?

I have a dynamic inputs, which I can add and delete a row with inputs, there are inputs of material-ui for timepicker, which having an input with her icon of a clock when I click on it the clock will appear.我有一个动态输入,我可以添加和删除带有输入的行,还有用于 timepicker 的 material-ui 输入,当我点击它时,它有一个带有时钟图标的输入,时钟会出现。 but the values of this input cannot change with the clock.但该输入的值不能随时钟变化。

My code is :我的代码是:

import { TimePicker } from "material-ui-time-picker";
import {
  Input as Time,
  Dialog as Clock,
  DialogActions,
  Button as ButtonOk
} from "@material-ui/core";
  constructor(props) {
    super(props);
    this.state = {
      isOpenS: false,
      isOpenE: false,
      start: moment().format("HH:MM"),
      end: moment().format("HH:MM"),
      tranches: [
        { start: moment().format("HH:MM"), end: moment().format("HH:MM") }
      ]
    };

    this.ajouterTranche = this.ajouterTranche.bind(this);
    this.supprimerTranche = this.supprimerTranche.bind(this);
    this.handleKeyboardStartChange = this.handleKeyboardStartChange.bind(this);
  }


  openDialogS = () => this.setState({ isOpenS: true });
  closeDialogS = () => this.setState({ isOpenS: false });
  backdropClickS = () => this.setState({ isOpenS: false });
  handleDialogStartChange = (i, newValue) => {
    const hours = newValue
      .getHours()
      .toString()
      .padStart(2, "0");
    const minutes = newValue
      .getMinutes()
      .toString()
      .padStart(2, "0");
    const textValue = hours + ":" + minutes;
    // this.setState({ start: textValue });
    this.state.tranches[i] = Object.assign({}, this.state.tranches[i], {
      start: textValue
    });
    this.setState({
      tranches: this.state.tranches
    });
  };

  handleKeyboardStartChange = (i, event) => {
    const rowDataCopy = this.state.tranches.slice(0);
    rowDataCopy[i] = Object.assign({}, rowDataCopy[i], {
      start: event.target.value
    });
    this.setState({
      tranches: rowDataCopy
    });
  };
  createDateFromTextValue = (i, value) => {
    const splitParts = value.split(":");
    return new Date(1970, 1, 1, splitParts[0], splitParts[1]);
  };

  openDialogE = () => this.setState({ isOpenE: true });
  closeDialogE = () => this.setState({ isOpenE: false });
  handleDialogEndChange = newValue => {
    const hours = newValue
      .getHours()
      .toString()
      .padStart(2, "0");
    const minutes = newValue
      .getMinutes()
      .toString()
      .padStart(2, "0");
    const textValue = hours + ":" + minutes;
    this.setState({ end: textValue });
  };
  handleKeyboardEndChange = (i, event) => {
    // On va copier le tableau de tranches
    const rowDataCopy = this.state.tranches.slice(0);
    // On va jouter cette valeur changée au tableau de tranches
    rowDataCopy[i] = Object.assign({}, rowDataCopy[i], {
      end: event.target.value
    });
    this.setState({
      tranches: rowDataCopy
    });
  };
  createDateFromTextValue = value => {
    const splitParts = value.split(":");
    return new Date(1970, 1, 1, splitParts[0], splitParts[1]);
  };


  ajouterTranche = () => {
    this.setState(prevState => ({
      tranches: [...prevState.tranches, ""]
    }));
  };

  supprimerTranche = idx => () => {
    const rowDataCopy = this.state.tranches.slice(0);
    rowDataCopy.splice(1, 1);
    this.setState({
      tranches: rowDataCopy
    });
  };
render() {

    console.log(this.state.start);
    return (

      <div>
        {this.state.tranches.map((el, i) => (
          <Row key={i}>
            <Col span={12} />
            <Col span={12}>
              <Row>
                <Col span={8}>
                  &nbsp; &nbsp; &nbsp;
                  <label className="pt-label .modifier">
                    <strong>Heure de début</strong>
                  </label>
                  <br />
                  <Time
                    value={el.start}
                    onChange={time => this.handleKeyboardStartChange(i, time)}
                    style={heure}
                    disableUnderline={true}
                    inputComponent={TextMaskCustom}
                    endAdornment={
                      <InputAdornment position="end" style={{ opacity: "0.4" }}>
                        <IconButton onClick={this.openDialogS}>
                          <AccessTime />
                        </IconButton>
                      </InputAdornment>
                    }
                  />
                  <Clock
                    maxWidth="xs"
                    open={this.state.isOpenS}
                    onBackdropClick={this.closeDialogS}
                  >
                    <TimePicker
                      mode="24h"
                      value={this.createDateFromTextValue(this.state.start)}
                      onChange={time => this.handleDialogStartChange(i, time)}
                    />
                    <DialogActions>
                      <ButtonOk onClick={this.closeDialogS} color="primary">
                        Ok
                      </ButtonOk>
                    </DialogActions>
                  </Clock>
                  <br />
                </Col>
                <Col span={8}>
                  &nbsp; &nbsp; &nbsp;
                  <label className="pt-label .modifier">
                    <strong>Heure de fin</strong>
                  </label>
                  <br />
                  <Time
                    value={el.end}
                    onChange={time => this.handleKeyboardEndChange(i, time)}
                    style={heure}
                    disableUnderline={true}
                    inputComponent={TextMaskCustom}
                    endAdornment={
                      <InputAdornment position="end" style={{ opacity: "0.4" }}>
                        <IconButton onClick={this.openDialogS}>
                          <AccessTime />
                        </IconButton>
                      </InputAdornment>
                    }
                  />
                  <Clock
                    maxWidth="xs"
                    open={this.state.isOpenE}
                    onBackdropClick={this.closeDialogE}
                  >
                    <TimePicker
                      mode="24h"
                      value={this.createDateFromTextValue(this.state.end)}
                      onChange={this.handleDialogEndChange}
                    />
                    <DialogActions>
                      <ButtonOk onClick={this.closeDialogE} color="primary">
                        Ok
                      </ButtonOk>
                    </DialogActions>
                  </Clock>
                  <br />
                </Col>
                <Col span={8}>
                  {i === 0 ? (
                    <>
                      <br />
                      &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
                      &nbsp;
                      <Icon
                        type="plus-circle"
                        theme="twoTone"
                        twoToneColor="#52c41a"
                        onClick={this.ajouterTranche}
                      />
                      <br />
                    </>
                  ) : (
                    <>
                      <Icon
                        type="close-circle"
                        theme="twoTone"
                        twoToneColor="red"
                        onClick={this.supprimerTranche(i)}
                      />
                      <Icon
                        type="plus-circle"
                        theme="twoTone"
                        twoToneColor="#52c41a"
                        onClick={this.ajouterTranche}
                      />
                      <br />
                    </>
                  )}
                </Col>
              </Row>
            </Col>
          </Row>
        ))}
      </div>


    );
  }
}

My sandbox code is : https://codesandbox.io/s/182oy5995l我的沙箱代码是: https : //codesandbox.io/s/182oy5995l

When I put a value on the input and I click on the clock, I get the moment value of the clock and not the value which I put on the input.当我在输入上放置一个值并点击时钟时,我得到的是时钟的时刻值,而不是我在输入上放置的值。 I want when I change the time from the clock, the input will be change and vice versa.我希望当我改变时钟的时间时,输入会改变,反之亦然。

How can I fix it ?我该如何解决?

I'm going to set you on the right track.我会让你走上正轨。 I think if you get this, you'll be able to quickly fix the rest of the problems.我想如果你得到这个,你将能够快速解决其余的问题。 I don't really know what you're trying to do with the start and end though.我真的不知道你想用开始和结束做什么。 So what I've done will only work on the timepicker and you can use this to fix the keyboard thing again.所以我所做的只能在时间选择器上工作,你可以用它来再次修复键盘问题。

Here is my forked version这是我的分叉版本
https://codesandbox.io/s/2xm39130kn https://codesandbox.io/s/2xm39130kn

When you call handleDialogStartChange with multiple objects, you can't just modify one state.当您使用多个对象调用handleDialogStartChange时,您不能只修改一种状态。 Unless they're all supposed to share the same time.除非他们都应该共享同一时间。 That seems pointless.这似乎毫无意义。

I modified your timepicker onChange function to onChange={time => this.handleDialogStartChange(i, time)} so you can push the index as well so you know which one you want to work with.我将您的 timepicker onChange 函数修改为onChange={time => this.handleDialogStartChange(i, time)}以便您也可以推送索引,以便您知道要使用哪个索引。

I modified your timepicker value function to value={this.createDateFromTextValue(el.start)} so you're referencing the individual element, not the original state variable.我将您的 timepicker 值函数修改为value={this.createDateFromTextValue(el.start)}以便您引用单个元素,而不是原始状态变量。

Then in andleDialogStartChange modify the the state of the tranches where you're storing these times, using that index.然后在andleDialogStartChange使用该索引修改您存储这些时间的批次的状态。 You'll get a warning not to modify state like this, but so long as you're using it in conjunction with setState, this.setState({ tranches: this.state.tranches });你会收到一个警告,不要像这样修改状态,但只要你将它与 setState, this.setState({ tranches: this.state.tranches });结合使用this.setState({ tranches: this.state.tranches }); , it's a legal operation. ,这是合法的操作。

handleDialogStartChange = (i, newValue) => {
    const hours = newValue
      .getHours()
      .toString()
      .padStart(2, "0");
    const minutes = newValue
      .getMinutes()
      .toString()
      .padStart(2, "0");
    const textValue = hours + ":" + minutes;
    this.state.tranches[i].start = textValue;
    this.state.tranches[i].end = textValue;
    this.setState({ tranches: this.state.tranches });
    this.setState({ start: textValue });
  };

为了解决我得到了时钟并选择了小时,但它没有改变,value={el.start}更改为value={this.state.start}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM