简体   繁体   中英

why attribute not working with React-Bootstrap Button?

I'm trying to set setCustomValidity for my input but it's not working with React-Bootstrap Button component. It's works fine with "standard" button. In my app form and Button are in diffrent components.

live demo try set invalid date and click

let { Button } = ReactBootstrap;

class MyComponent extends React.Component {
  formValidation() {
    let inp = document.getElementById("input");
    inp.setCustomValidity("test");
  }

  render() {
    return (
      <div>
        <form id="myform">
          <input id="input"
            type="datetime-local"
           />

        </form>
        <button form="myform" onClick={this.formValidation}>Click </button>
        <Button form="myform" onClick={this.formValidation}>React-Bootstrap btn</Button>

      </div>
    );
  }
}

The attribute form="myform" on the Bootstrap Button is passed down to the button component as a prop which is not handled by react-bootstrap.

Also the default type for a button element is submit whereas for the Bootstrap Button component it is button and hence it doesnt work for you.

You would rather specify type="submit" on bootstrap button and make use of ref instead of direct DOM handling

Code:

class MyComponent extends React.Component {
  constructor(){
    super();
    this.formValidation = this.formValidation.bind(this);
  }
  formValidation (){
    this.input.setCustomValidity("test");
  }

  render() {
    return (
      <div>
        <form id="myform">
          <input ref={ref =>this.input=ref}
            type="datetime-local"
           />

        </form>
        <button form="myform" onClick={this.formValidation}>Click </button>
        <Button type="submit" form="myform" onClick={this.formValidation}>React-Bootstrap btn</Button>

      </div>
    );
  }
}

CODEPEN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM