我可以制作一个单独的组件来呈现多个输入吗?

时间:2019-03-28 15:05:32

标签: javascript reactjs

我有一个名为inputArea的组件,它从输入字段中接收信息并将其发送到服务器:

export default class InputArea extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      draw_number: '',
      user_number_1: '',
      user_number_2: '',
      user_number_3: '',
      user_number_4: '',
      user_number_5: '',
      user_number_6: '',
    }
  }

  submitHandler = () => {
    let { draw_number, ...rest } = this.state;
    let request = {
      numbers: Object.keys(rest).map(key => parseInt(rest[key])),
      draws: parseInt(draw_number)
    };
    this.props.onSubmit(request);
  }

  inputHandler = event => this.setState({[event.target.name]: event.target.value});

  render() {

      return (
        <InputField>
          <InputWrapper>
            {/* <Input > */}
            <Label>1st number</Label>
            <Input name="user_number_1" type="number" maxlength="2" value={this.state.user_number_1} onChange={this.inputHandler} required></Input>
            <Label>2nd number</Label>
            <Input name="user_number_2" type="number" maxlength="2" value={this.state.user_number_2} onChange={this.inputHandler} required></Input>
            <Label>3rd number</Label>
            <Input name="user_number_3" type="number" maxlength="2" value={this.state.user_number_3} onChange={this.inputHandler} required></Input>
            <Label>4th number</Label>
            <Input name="user_number_4" type="number" maxlength="2" value={this.state.user_number_4} onChange={this.inputHandler} required></Input>
            <Label>5th number</Label>
            <Input name="user_number_5" type="number" maxlength="2" value={this.state.user_number_5} onChange={this.inputHandler} required></Input>
            <Label>6th number</Label>
            <Input name="user_number_6" type="number" maxlength="2" value={this.state.user_number_6} onChange={this.inputHandler} required></Input>
            <Label>Number of draws:</Label>
            <Input name="draw_number" type="number" value={this.state.draw_number} onChange={this.inputHandler} required></Input>
          </InputWrapper>
          <Button type="button" onClick={this.submitHandler}>Let's win!</Button>
        </InputField>
      )
  }
}

我想缩短此组件,以便它不会具有可重复的值。 我可以编写一个新组件来接收“文本”和“输入”并呈现输入值(draw_numbers除外)吗?

1 个答案:

答案 0 :(得分:1)

如果您想以编程方式生成这些输入,则可以做出一些可以迭代状态的操作:

{Object.entries(this.state).map(([key, value]) => {
  if (key.includes("user_number")) {
    return <div key={key}>
        <Label>Number {key.replace(/\D*/, '')}</Label>
        <Input name={key} type="number" maxlength="2" value={value} onChange={this.inputHandler} required></Input>
      </div>
  }
})}