【问题标题】:Get event target name (not value) from React Bootstrap Form?从 React Bootstrap Form 获取事件目标名称(不是值)?
【发布时间】:2020-04-27 05:24:50
【问题描述】:

我有一个 React Bootstrap 表单组件

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

我只需要能够获取用户在其中输入的输入框的名称/引用,以便我可以动态更新状态。我已经使用标准表单做到了这一点:


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

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

这是我的示例 React Bootstrap 表单

    <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
    })

这对于标准表单(非 React Boostrap 表单)工作得很好,它确实为用户正在积极更新/正在输入的输入返回正确的值,但是 event.target.name不起作用。

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

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

【问题讨论】:

    标签: javascript html reactjs forms react-bootstrap


    【解决方案1】:

    get its reference name,将值添加到道具name 就可以了

    之前:

    <Form.Control type="text" placeholder="userId" ref={this.userId} onChange={this.handleInputChange}/>
    

    之后:

    <Form.Control type="text" name="userId" placeholder="userId" ref={this.userId} onChange={this.handleInputChange}/>
    

    【讨论】:

    • 多哈。我在那里有这个,它不工作(所以我想)但它现在肯定工作。 smh 我笨 thx
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-20
    • 1970-01-01
    • 1970-01-01
    • 2018-05-19
    相关资源
    最近更新 更多