簡體   English   中英

react-bootstrap:清除元素值

[英]react-bootstrap: clear element value

我試圖在onClick事件后清除我的輸入字段。

我正在使用react-bootstrap庫,雖然有getValue()方法,但沒有setValue(value)方法。

我偶然發現了這個 討論

為了在提交后簡單地清理表單,我不完全理解他們的建議。

畢竟,如果我使用簡單的 HTML <input>而不是react-bootstrap ,我可以通過元素ref獲取節點並將其值設置為空字符串或其他內容。

什么被認為是清理我的 react-bootstrap <Input />元素的反應方式?

將狀態存儲在 React 組件中,通過 props 設置元素值,通過事件回調獲取元素值。 這是一個例子:

這是直接取自他們的文檔的示例。 我剛剛添加了一個clearInput()方法來向您展示您可以通過更新組件的狀態來清除輸入。 這將觸發重新渲染,這將導致輸入值更新。

const ExampleInput = React.createClass({
  getInitialState() {
    return {
      value: ''
    };
  },

  validationState() {
    let length = this.state.value.length;
    if (length > 10) return 'success';
    else if (length > 5) return 'warning';
    else if (length > 0) return 'error';
  },

  handleChange() {
    // This could also be done using ReactLink:
    // http://facebook.github.io/react/docs/two-way-binding-helpers.html
    this.setState({
      value: this.refs.input.getValue()
    });
  },

  // Example of how you can clear the input by just updating your state
  clearInput() {
    this.setState({ value: "" });
  },

  render() {
    return (
      <Input
        type="text"
        value={this.state.value}
        placeholder="Enter text"
        label="Working example with validation"
        help="Validation is based on string length."
        bsStyle={this.validationState()}
        hasFeedback
        ref="input"
        groupClassName="group-class"
        labelClassName="label-class"
        onChange={this.handleChange} />
    );
  }
});

對於我目前正在做的事情,我真的認為沒有必要通過 setState/Flux 來控制 Input 組件的值(也就是我不想處理所有樣板文件)......所以這里有一個要點我所做的。 希望 React 大神原諒我。

import React from 'react';
import { Button, Input } from 'react-bootstrap';

export class BootstrapForm extends React.Component {

  constructor() {
    super();
    this.clearForm = this.clearForm.bind(this);
    this.handleSave = this.handleSave.bind(this);
  }

  clearForm() {
    const fields = ['firstName', 'lastName', 'email'];
    fields.map(field => {
      this.refs[field].refs['input'].value = '';
    });
  }

  handleSubmit() {
    // Handle submitting the form
  }

  render() {
    return (
      <div>
        <form>
          <div>
            <Input
              ref='firstName'
              type='text'
              label='First Name'
              placeholder='Enter First Name'
            />
            <Input
              ref='lastName'
              type='text'
              label='Last Name'
              placeholder='Enter Last Name'
            />
            <Input
              ref='email'
              type='email'
              label='E-Mail'
              placeholder='Enter Email Address'
            /> 
            <div>
              <Button bsStyle={'success'} onClick={this.handleSubmit}>Submit</Button>
              <Button onClick={this.clearForm}>Clear Form</Button>
            </div>
          </div>
        </form>
      </div>
    );
  }
}

如果您使用 FormControl 作為輸入,並且您想使用 ref 來更改/從中獲取值,則使用 inputRef 而不是 ref

<FormControl inputRef={input => this.inputText = input} .../>

並使用它來獲取/更改其值:

this.inputText.value

這對我有用,以防其他人正在尋找答案:D

您可以通過使用訪問 react-bootstrap 的值

console.log(e.target.form.elements.fooBar.value)

您可以使用清除它們

e.target.form.elements.fooBar.value = ""
    import React from 'react';
    import {Button, Form} from 'react-bootstrap';

    export default function Example(props) {

    const handleSubmit = (e) => {
    // Handle submitting the form
    }

    const resetSearch = (e) => {
      e.preventDefault();
      e.target.form.elements.fooBar.value = ""
    }

    render() {
      return (
          <Form onSubmit={handleSubmit} onReset={resetSearch} >
             <Form.Control type="input" name="fooBar" />  
             <Button type="submit">  Submit  </Button> 
             <Button onClick={resetSearch} type="submit" > Reset  </Button> 
          </Form>
          );
       }
    }

你也可以只使用 ReactDOM:

<FormControl
  componentClass="select"
  ref="sStrike">
  <option value="-">Select&hellip;</option>
  <option value="1">1</option>
  <option value="2">2</option>
</FormControl>

現在一個不同的 FormControl 觸發一個onChange={handleChange}並且在那個處理程序中你可以只標識ref並設置為默認值:

ReactDOM.findDOMNode(this.refs.sStrike).value = '-';

這會將選擇框設置為“默認”值。

只需在表單中添加一個屬性 type="reset" 的按鈕

<Button variant="primary" type="reset">Reset</Button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM