从React Bootstrap表格中获取事件目标名称(不是值?)>

问题描述 投票:0回答:1

我有一个React Bootstrap表单组件

https://react-bootstrap.github.io/components/forms/#forms

我只需要能够获得用户在其中输入的输入框的名称/引用,因此我可以动态更新状态。我已经使用以下标准表格完成了此操作:


this.setState({
           [event.target.name]: event.target.value
        })

但是我想使用React的Bootstrap表单。我已经可以获取Form输入的值,但是找不到找到其引用名称的方法(例如,如果输入框用于DealerName,则无法获取字符串'dealerName',因此可以动态更新它)而不是必须将状态属性名称硬编码为值来更新它),这样我就可以动态更新状态。没有这个,我将不得不为我拥有的所有不同形式创建多个单独的函数。

这是我的示例React Bootstrap Form

    <Form>
          <Form.Group controlId="formDealersAdd">
          <Form.Label>userId:</Form.Label>
          <Form.Control type="text" placeholder="userId" ref={this.userId} onChange={this.handleInputChange}/>
          <Form.Label>dealerName:</Form.Label>
          <Form.Control type="text" placeholder="dealerName" ref={this.dealerName} onChange={this.handleInputChange} />
          <Form.Label>dealer id:</Form.Label>
          <Form.Control type="text"  placeholder={did} ref={this.did} onChange={this.handleInputChange} />
          <Button variant="secondary" size="lg" onClick={this.handleDealersAddFormClick}>SUBMIT</Button>{' '}
          </Form.Group>
    </Form>

我的构造函数

看起来像这样:
    class App extends Component {

      constructor(props) {
        super(props);

        this.userId= React.createRef();
        this.dealerName = React.createRef();
        this.did = React.createRef();

        this.state = {
          userId: '',
          dealerName: '',
          did: '',
        };
      }
    }

和我的handleInputChange

函数:
    handleInputChange = (event) => {
        event.preventDefault()

   // manually hardcoding it like this causes issues and makes my code bad
         this.setState({
          userId: this.userId.current.value,
          dealerName: this.dealerName.current.value,
          did: this.did.current.value
        })
      }

我原本是通过简单地用]设置状态来处理inputChange的。

    this.setState({
    [event.target.name]: event.target.value
    })

并且对于标准表单(非反应Boostrap表单)而言,它工作得很好,并且它确实为用户正在主动更新/输入的输入返回正确的值,但是event.target.name却没有工作。

因此,如您在上面看到的,我只是手动对要在[[state对象中更新的值进行了硬编码,但这很麻烦,并且当用户单击以查看我网站上的新表单和属性时,会导致错误为null,状态会尝试更新,因此会崩溃。

有没有一种方法可以更新我的React Bootstrap表单输入的状态属性,类似于我使用[event.target.name]:常规表单的event.target.value?

我有一个React Bootstrap表单组件https://react-bootstrap.github.io/components/forms/#forms我只需要能够获得用户在其中键入内容的输入框的名称/引用,我可以...

javascript html reactjs forms react-bootstrap
1个回答
0
投票
对于get its reference name,将值添加到道具name会很好

之前:

© www.soinside.com 2019 - 2024. All rights reserved.