简体   繁体   English

react.js-如何在动态生成的按钮成功添加元素?

[英]react.js - how to add element on success in dynamically generated button?

I have dynamically generated component with textfields and buttons. 我有带有文本字段和按钮的动态生成的组件。 Each button do the ajax request. 每个按钮都执行ajax请求。 It's all working fine. 一切都很好。 However, I want to display the success message or error message on button itself, adding some icon on it. 但是,我想在按钮本身上显示成功消息或错误消息,并在其上添加一些图标。 This is where I got stuck. 这就是我卡住的地方。 I setup the flag and change the state, but it will change on all the buttons as expected. 我设置了标志并更改了状态,但是它将按预期在所有按钮上更改。 I also tried to change the current target, but the reference didn't work in success callback. 我也尝试更改当前目标,但是该引用在成功回调中不起作用。 Can someone please help me with this. 有人可以帮我吗

    const FormGroup = ({index, type, field, value, onChange, spinner, isLoading, error, buttonType, brandList, handleBrandConfiguration, checkAvailability, handleCaseType, options, handlerRemoveItem})=> {
  return(
    <div>
      <div className="form-group">
        <label>{index}</label>
        <input type="text"
          name={field}
          className="form-control"
          value={value}
          onChange={onChange}
          />
          <select className="form-control" defaultValue="" onChange={handleBrandConfiguration}>
            <option value="">Please select brand</option>
            {brandList}
          </select>
        <select className="form-control" defaultValue="" onChange={handleCaseType}>
          <option value="">Please select case template</option>
          {options}
        </select>
        <button
          type={buttonType}
          className={classname(isLoading ? error ? "button button-danger" : "button button-success" : error ? "button button-danger" : "button button-primary")}
          onClick={checkAvailability}>
          <i className={classname(spinner ? error ? '': "fa fa-spinner fa-spin": '')}></i> {isLoading ? error ? 'Not Found' :<i className="fa fa-check fa-2" aria-hidden="true"></i> : error ? 'Not Found': 'Check Availability'}</button>
        <input
          type="button"
          className="button button-danger"
          value="Remove Item"
          onClick={handlerRemoveItem}/>
        </div>
      </div>
  );
};

Thanks 谢谢

If you move your checkAvailability and result of api request to FormControl component you can set error and success for single component. 如果将checkAvailability和api请求的结果移动到FormControl组件,则可以为单个组件设置错误和成功。

For Example: 例如:

class FormGroup extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      availabilityResult: null
    };
  }
  callApi(username){
    return(axios.get('https://api.github.com/users/' + username));
  }
  onChange(e){
    this.setState({
      itemCode: e.target.value
    });
  }

  checkAvailability(e){
    const username = this.state.itemCode;
    let currentValue = e.currentTarget.value;
    //ajax call goes here
    this.callApi(username).then(response => {
      const login = response.data.login;
      this.setState({
        availabilityResult: (login === 'mesmerize86')
      });
    }).catch(err => {
      console.log(err);
    });
  }

  render() {
    const {index, field, value, handleRemoveItem} = this.props;
    let inputState = '';
    if (this.state.availabilityResult === true) inputState = 'button-success';
    else if (this.state.availabilityResult === false) inputState = 'button-danger';

    return(
      <div className="form form-inline">
        <div className="form-group">
          <label>{index}</label>
          <input type="text"
            name={field}
            className="form-control"
            value={value}
            onChange={this.onChange.bind(this)}
          />
          <input
            type="button"
            className={`button button-primary ${inputState}`}
            value="Check Availability"
            onClick={this.checkAvailability.bind(this)} />
            <input
              type="button"
              className="button button-danger"
              value="Remove Item"/>
            </div>
          </div>
        )    
      }
    }


    class Main extends React.Component {
      constructor(props){
        super(props);
        this.state = {
          rowList : [],
          itemCodes: [],
          itemCode: ''
        }
      }
      handlerAddRow(){
        const rowList = this.state.rowList.concat(FormGroup);
        this.setState({ rowList });
      }      
      handleRemoveItem(){
        console.log('remove Item');
      }      
      render(){
        const rowList = this.state.rowList.map((row, index) => {
          return (<FormGroup key={index} index={index+1} field={`"itemCode_"${index}`} />);
        });

        return(
          <div className="container">
            <input type="button" value="Add a row" className="button button-primary" onClick={this.handlerAddRow.bind(this)} />    <i class="fa fa-spinner" aria-hidden="true"></i>
            {rowList}
          </div>
        );
      }
    }

    ReactDOM.render(<Main />, document.getElementById('app'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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