@dollar1610

Пропадает фокус с input при изменении?

Ввожу данные в input, после того как я ввел 1 символ, фокус с него пропадает. Но если полностью стереть данные с input, то фокус не пропадает. Предполагаю, что загвоздка в функции changeDiscount
Ниже код страницы
Код страницы
export default class InvoiceCreate extends Component {
    constructor(props) {
        super(props);
        this.state = {
            products: [],
            customers:[],
            valueCustomer:'',
            valueProducts:'',
            dataTable: [],
            total:0
        };
        this.loadData = this.loadData.bind(this);
        this.add = this.add.bind(this);
        this.changeStateCustomer = this.changeStateCustomer.bind(this);
        this.changeStateProduct = this.changeStateProduct.bind(this);
        this.funcCustomers = this.funcCustomers.bind(this);
        this.funcProducts = this.funcProducts.bind(this);
        this.price = this.price.bind(this);
        this.changeDiscount =this.changeDiscount.bind(this);
        this.sendForm = this.sendForm.bind(this);
        this.nameAutoFocus = true;
    }
    componentDidMount() {
        this.loadData();
        this.nameAutoFocus = false;
    }
    sendForm() {
        let content
    }
    changeDiscount(e) {
        if (e.target.value==='') return null;
        if ((e.target.value!=='')&&(e.target.value)) {
            let discount_id = e.target.parentElement.parentElement.parentElement.dataset.id;
            let dataTable=this.state.dataTable;
            dataTable[discount_id].qty = e.target.value;
            let total=0;
            for (let i=0;i<dataTable.length;i++) {
                total += dataTable[i].price*(1-dataTable[i].qty/100);
            }
            this.setState({
                total:total,
                dataTable:dataTable
            });
            console.log('test0');
        }
    }
    price(data) {
        let name = this.state.valueProducts.value;
        for(let i=0;i<data.length;i++) if (name===data[i].name)  return  (data[i].price);
    }
    funcCustomers () {
        let props = {
            properties: this.state.customers
        };
        selectCustomers(props);
        console.log('test1');
        return selectCustomers(props);
    }

    funcProducts () {
        let props = {
            properties: this.state.products
        };
        selectProducts(props);
        console.log('test2');
        return selectProducts(props);
    }
    add(e) {
        e.preventDefault();
        e.persist();
        let dataTable = this.state.dataTable ;
        fetch('/api/products')
            .then((response) => {
                return response.json()
                    .then((data) => {
                        dataTable.push({
                            name: this.state.valueProducts.value,
                            price: this.price(data),
                            qty: document.getElementById('formControlText').value,
                        });
                        let discount = document.getElementById('formControlText').value / 100;
                        let total = 0;
                        for (let i = 0; i < dataTable.length; i++) {
                            total += dataTable[i].price
                        }
                        total = total * (1 - discount);
                        this.setState({
                            total: total
                        });
                    });
            });
    }
    changeStateCustomer = (valueCustomer) => {
        this.setState({valueCustomer:valueCustomer});
    };
    changeStateProduct = (valueProduct) => {
        this.setState({valueProducts:valueProduct});
    };
    loadData() {
        let customers=[],
        products = [];
        fetch('/api/products')
            .then((response) =>
                response.json()
                    .then((data) =>{
                        for(let i=0; i<data.length;i++) products[i] = data[i].name
                        this.setState({products:products})
                    })
            );
        fetch('/api/customers')
            .then((response) =>
                response.json()
                    .then((data) =>{
                        for(let i=0; i<data.length;i++) customers[i] = data[i].name;
                        this.setState({customers:customers})
                    })
            )
    }

render() {
    return (
        <div className='container'>
            <PageHeader>Create Invoice</PageHeader>
            <form onSubmit={this.add}>
                <FormGroup  controlId='formControlText' style={{width:20+'%'}}>
                    <ControlLabel>Discount (%)</ControlLabel>
                    <FormControl/>
                </FormGroup>
                <label>Customer</label>
                <Select
                    name="form-field-name"
                    style={{width:40+'%'}}
                    value={this.state.valueCustomer}
                    onChange={this.changeStateCustomer}
                    options={this.funcCustomers()}
                />
                <label>Add products</label>
                <Select
                    name="form-field-name"
                    style={{width:40+'%'}}
                    value={this.state.valueProducts}
                    onChange={this.changeStateProduct}
                    options={this.funcProducts()}
                />
                <Button type="submit" bsStyle="primary">Add</Button>
            </form>
            <Table  responsive>
                <thead>
                <tr>
                    <th>Name</th>
                    <th>Price</th>
                    <th>Qty</th>
                </tr>
                </thead>
                <LoadTableData focus={this.nameAutoFocus} discount={this.changeDiscount} data={this.state.dataTable} />
            </Table>
            <PageHeader>Total:
                <NumberFormat displayType={'text'} value={this.state.total} decimalSeparator={'.'} decimalScale={2}/>
            </PageHeader>
            <Button bsStyle="success" onClick={this.sendForm}>
                Submit
            </Button>
        </div>
    )
}
}


Здесь добавляется input
Тут лежит input
import React from 'react';
import ModalDelete from './modals/modal_delete';
import { FormGroup,FormControl } from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';

export default function (props) {
    let datas = props.data;
    let count=-1;
    let listDatas = datas.map((data) => {
        count++;
        return  <tr data-id={count} key={data.toString()+Math.random()*1000}>{transform(data, props.discount, props.focus)}</tr>;
    });
    return (
        <tbody>{listDatas}</tbody>
    );
}

function transform(mass, discount, focus) {
    let props = [];
    let count=0;
    for (let key in mass) {
        props.push(mass[key])
    }
  //  props.push(<ModalDelete loadData={loadData} />);
    return props.map((prop) => {
        if (count===2) return (
        <td key={prop.toString()}>
            <FormGroup  controlId='formControlText' style={{width:20+'%'}}>
                <FormControl
                    type="text"
                    defaultValue={prop}
                    bsClass="lg"
                    onChange={discount}
                    autoFocus={focus}
                    key={1000}
                />
            </FormGroup>
        </td>
    ); console.log('test4');
        count++;
        return <td key={prop.toString()}>{prop}</td>;
    });
}

  • Вопрос задан
  • 2177 просмотров
Решения вопроса 1
@dollar1610 Автор вопроса
Каждый раз когда меняется значение в input оно тут же записывается в стейт а затем рендерится, поэтому сбрасывается фокус.
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы