Enable or disable a button based on a TextField value in React.js

淺唱寂寞╮ 提交于 2020-08-27 07:51:11

问题


I am making a form like

I want the add button to be active whenever user is changing the "Tags" input text.

I am using material-ui and I made a Input component.

  const SingleInput = (props) => ( 
    <Fragment>
      <FormControl margin="normal" required fullWidth>
        <TextField
        id={props.id}
        type={props.type}
        name={props.name}
        label={props.label}
        value={props.content}
        variant={props.variant}
        placeholder ={props.placeholder}
        onChange={props.controlFunc}>
        </TextField>
      </FormControl>
    </Fragment>
  );
  export default SingleInput;

and I import this into my form and like:

class AddCompanyForm extends React.Component {
  constructor() {
    super();
    this.state = {
      company_name: "",
      company_description: "",
      company_tag: "",
      company_tags: "",
      company_contact: "",
      disabled: true
    };

    this.handleOnSubmit = this.handleOnSubmit.bind(this);
    this.handleOnChange = this.handleOnChange.bind(this);
    this.handleOnSelect = this.handleOnSelect.bind(this);
  }
  handleOnChange(e) {
    e.preventDefault();
    this.setState({ [e.target.name]: e.target.value });
    this.setState({ disabled: false });
    console.log("teg", this.state.company_tag.length);
    console.log("cont", this.state.company_contact.length);
    if (this.state.company_tag.length == 1) {
      this.setState({ disabled: true });
    }
  }

  handleOnSubmit(e) {
    e.preventDefault();
    this.props.createCompany(this.state);
  }

  handleOnSelect(e) {
    e.preventDefault();
    chipsValue.push(this.state.company_tag);
    this.setState({
      company_tags: chipsValue,
      company_tag: "",
      disabled: true
    });
  }

  render() {
    return (
      <Paper style={styles.paper}>
        <Avatar>
          <LockIcon />
        </Avatar>
        <Typography variant="headline">Add a New Company</Typography>
        <form onSubmit={this.handleOnSubmit}>
          <SingleInput
            id={"company_name"}
            type={"company_name"}
            name={"company_name"}
            label={"Company Name"}
            content={this.state.company_name}
            controlFunc={this.handleOnChange}
            variant={"filled"}
          />
          <SingleInput
            id={"company_description"}
            type={"company_description"}
            name={"company_description"}
            label={"Description"}
            content={this.state.company_description}
            controlFunc={this.handleOnChange}
            variant={"filled"}
          />
          <SingleInput
            id={"company_tags"}
            type={"company_tags"}
            name={"company_tag"}
            label={"Tags (to add dropdown here!)"}
            content={this.state.company_tag}
            controlFunc={this.handleOnChange}
            variant={"filled"}
          />
          <Button
            disabled={this.state.disabled}
            onClick={this.handleOnSelect}
            variant="raised"
            color="secondary"
          >
            Add
          </Button>
          <SingleInput
            id={"company_contact"}
            type={"company_contact"}
            name={"company_contact"}
            label={"Contact"}
            content={this.state.company_contact}
            controlFunc={this.handleOnChange}
            variant={"filled"}
          />
          <Button type="submit" fullWidth variant="raised" color="primary">
            Add Company
          </Button>
        </form>
      </Paper>
    );
  }
}
const mapDispatchToProps = dispatch =>
  bindActionCreators(
    {
      createCompany
    },
    dispatch
  );
export default connect(
  null,
  mapDispatchToProps
)(AddCompanyForm);

Now the problem is even when I change "Company Name" or any other input button, the Add button becomes enabled.

Any help is very much appreciated.


回答1:


Check the example below using React Hooks for the button state, and the onChange property of the TextField to set it.

export default function TextFieldAndButton (props) {
  const [btnDisabled, setBtnDisabled] = useState(true)

  return (
    <>
        <TextField
          onChange={(text) => setBtnDisabled(!text.target.value)}
        />
        <Button disabled={btnDisabled}>OK</Button>
    </>
  )
}



回答2:


The problem here is that setState is async and you are using state values inside handleOnChange before it is updated. Either use setState callback to calculate disable or a better way is to calc disabled in render. This approach makes it much simpler and even works while rendering for the first time.

render() {
  const disabled = !this.state.company_tag.length;

  return (
    // ...
    <Button
      disabled={disabled}
      onClick={this.handleOnSelect}
      variant="raised"
      color="secondary"
    >
      Add
    </Button>
    // ...
  );
}


来源:https://stackoverflow.com/questions/52868369/enable-or-disable-a-button-based-on-a-textfield-value-in-react-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!