添加和删​​除动态输入字段

时间:2017-09-08 07:37:54

标签: javascript reactjs

我希望有一个动态数量的输入字段,并且还能够将其删除。我可以这样做,如果这只是客户端,但我从服务器获取数据,问题是我没有从服务器获取id,并且我需要能够动态更改字段数用户界面。

因为我也从服务器获取了一些字段,手动添加的id不再与项目数量同步。

我如何实现这一目标?

这是我的代码

let _id = 0;

function guid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
  }
  return s4() + s4();
}

class Rules extends React.PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      rules: {
        rule_regulations: {}
      },
      numberOfInput: []
    };
  }

  componentDidMount() {
    this.props.loadRules();
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.rules.size && nextProps.rules !== this.props.rules) {
      nextProps.rules
        .entrySeq()
        .map(([key, value]) => {
          this.setState(state => ({
            rules: {
              ...state.rules,
              rule_regulations: {
                ...state.rules.rule_regulations,
                [key]: value
              }
            },
            numberOfInput: [...state.numberOfInput, guid()]
          }));
        })
        .toArray();
    }
  }

  handleChange = e => {
    const { value, name } = e.target;
    this.setState({
      rules: {
        ...this.state.rules,
        rule_regulations: {
          ...this.state.rules.rule_regulations,
          [name]: value
        }
      }
    });
  };

  handleAddRules = e => {
    this.setState({
      numberOfInput: [...this.state.numberOfInput, guid()]
    });
  };

  handleRemoveRules = (e, num) => {
    e.preventDefault();
    this.setState({
      numberOfInput: this.state.numberOfInput.filter(input => input !== num)
    });
  };

  handleSave = e => {
    e.preventDefault();
    const obj = {
      rule_regulations: Object.values(this.state.rules.rule_regulations)
    };
    this.props.postRules(obj);
  };

  render() {
    const { numberOfInput } = this.state;
    return (
      <div className="basic-property">
        <span className="circleInputUi" onClick={this.handleAddRules}>
          +
        </span>
        <RulesInputContainer
          numberOfInput={numberOfInput}
          handleChange={this.handleChange}
          handleRemoveRules={this.handleRemoveRules}
          handleSave={this.handleSave}
          value={this.state.rules.rule_regulations}
        />
      </div>
    );
  }
}


const RulesInputContainer = props => {
  return (
    <div className="rules-input">
      {props.value &&
        Object.keys(props.value).map(key =>
          <RulesInput
            key={key}
            num={key}
            value={props.value}
            handleChange={props.handleChange}
            handleRemoveRules={props.handleRemoveRules}
          />
        )}
      <button className="button" onClick={props.handleSave}>
        Save
      </button>
    </div>
  );
};

export default RulesInputContainer;


const RulesInput = props => {
  return (
    <form className="form">
      <InputField
        label={`Rule ${props.num + 1}`}
        type="text"
        name={`${props.num}`}
        value={props.value[props.num] || ""}
        onChange={props.handleChange}
      />
      <Button onClick={e => props.handleRemoveRules(e, props.num)}>
        Remove
      </Button>
    </form>
  )
  }

我希望与服务器数据和客户端

同步

1 个答案:

答案 0 :(得分:-1)

您可以将服务器中返回的数据存储到组件state中。

componentDidMount() {
  this.loadRules();
}

loadRules() {
  let rules = this.props.loadRules();
  this.setState({rules});
}

您可以通过使用从服务器收到的数据设置state来保持同步。

此外,它与您的问题无关。由于RulesInputContainerRulesInput是表示组件,我认为您可以将它们组合成一个组件。

相关问题