Как получить доступ к данным ячейки таблицы в ответ - PullRequest
0 голосов
/ 29 сентября 2018

Я создал корзину с помощьюactjs, и теперь я передаю объект в корзину, и я могу добавить количество, после чего я буду автоматически рассчитывать промежуточную сумму продукта.Но теперь я должен рассчитать Total, используя это промежуточное значение.Итак, могу ли я узнать, как получить доступ к столбцу таблицы «промежуточный итог» и рассчитать общую стоимость приобретенных продуктов?

Я приложил таблицу ниже.

render(){
 const subtot =this.DrugsDetailsRequest.totalPrice*this.state.textInputValue1
        console.log(subtot);// this will get you the total
        const sum=sum+subtot;
        console.log(sum);
        return (

                <tr>
                    <td data-th="Product">
                        <p>{this.DrugsDetailsRequest.item_name}</p>
                    </td>
                    <td> Rs: {this.DrugsDetailsRequest.totalPrice}</td>
                    <td>
                        <input name="textInputValue1" type="number" className="form-control text-center"  onChange={ this.handleChange } />
                    </td>
                    <td className="text-center">
                        <input name="textInputValue2" type="text" className="form-control text-center" value={subtot}
                                onChange={ this.handleChange } />
                    </td>
                    <td className="actions">
                        <button className="btn btn-danger btn-sm" onClick={(e) => this.delete(this.DrugsDetailsRequest._id)}>Delete</button>
                    </td>
                </tr>

        );
    }
}

введите описание изображения здесь

Ответы [ 2 ]

0 голосов
/ 29 сентября 2018

в реакции, вы должны попытаться настроить визуализацию пользовательского интерфейса в соответствии с состоянием реакции.в вашем случае, если вы хотите получить доступ к промежуточному итогу, вы можете создать состояние компонента следующим образом:

class Cart extends React.Component {
constructor(props) {
  super(props);
  // initial cart state
  this.state = {
    total: 0,
    inCartItems: {
      ddd: {
        price: 12,
        quantity: 0,
        subtotal: 0,
      },
      www: {
        price: 45,
        quantity: 0,
        subtotal: 0,
      },
      e3400: {
        price: 45,
        quantity: 0,
        subtotal: 0,
      },
    },
  };
}
handleChange = (itemName, quantity) => {
  // set new inCartItems state
  // then use the updated state to calculate total by just sum up the subtotal in each items
}
render() {
  return (
    // your table content
    <div>
      {/*handle item number change like this*/}
      <input onChange={(e) => this.handleChange('ddd', e.target.value)} />
      <input onChange={(e) => this.handleChange('www', e.target.value)} />
      <input onChange={(e) => this.handleChange('e3400', e.target.value)} />
      <div className={'total'}>
        {this.state.total}
      </div>
    </div>
    // ....
  );
}
}
0 голосов
/ 29 сентября 2018

Это одно решение для вас: Использование ссылок

Для получения дополнительной информации вы можете прочитать здесь: Ссылки и DOM

Это пример того, что вам нужно.

class CustomTextInput extends React.Component {
      constructor(props) {
        super(props);
        // create a ref to store the textInput DOM element
        this.textInput = React.createRef();
        this.focusTextInput = this.focusTextInput.bind(this);
      }
    
      focusTextInput() {
        // Explicitly focus the text input using the raw DOM API
        // Note: we're accessing "current" to get the DOM node
        this.textInput.current.focus();
      }
    
      render() {
        // tell React that we want to associate the <input> ref
        // with the `textInput` that we created in the constructor
        return (
          <div>
            <input
              type="text"
              ref={this.textInput} />
    
            <input
              type="button"
              value="Focus the text input"
              onClick={this.focusTextInput}
            />
          </div>
        );
      }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...