background

ZYM colleague next door encountered a problem. When editing the form, the focus would be lost after each input character, so it was necessary to re-click the focus before continuing to input, as shown in the figure:







why

In the final analysis, the question is about key. In the original code, Components was in Render, but it fires after each setState, so each Components is a new variable, a new component.

import "./styles.css"; import React from "react"; import { Table, Input } from "antd"; import "antd/dist/antd.css"; export default class App extends React.Component { state = { tableInput: "", dataSource: [ { name: "blueju", password: "blueju", type: 1 } ] }; handleInputChange = (e, text, index) => { const dataSource = JSON.parse(JSON.stringify(this.state.dataSource)); dataSource[index].name = e.target.value; this.setState({ dataSource }); }; render() { const components = { table(props) { return <table>{props.children}</table>; }}; return ( <div className="App"> <h1>Hello CodeSandbox</h1> <h2>Start editing to see some magic happen! </h2> <Table dataSource={this.state.dataSource} components={components}> <Table.Column dataIndex="name" title="name" render={(text, record, index) => { if (record.type === 1) { return ( <Input // key={index} value={this.state.tableInput} onChange={(e) => { // this.handleInputChange(e, text, index); this.setState({ tableInput: e.target.value }); }} / >); } if (record.type === 2) { return text; } }} /> </Table> <Input.TextArea value={JSON.stringify(this.state.dataSource, null, 2)} autoSize /> </div> ); }}

Revised:

Take Components outside of a component, but you can also take them inside if they don’t need to be shared with other components.

import "./styles.css"; import React from "react"; import { Table, Input } from "antd"; import "antd/dist/antd.css"; const components = { table(props) { return <table>{props.children}</table>; }}; export default class App extends React.Component { state = { tableInput: "", dataSource: [ { name: "blueju", password: "blueju", type: 1 } ] }; handleInputChange = (e, text, index) => { const dataSource = JSON.parse(JSON.stringify(this.state.dataSource)); dataSource[index].name = e.target.value; this.setState({ dataSource }); }; render() { return ( <div className="App"> <h1>Hello CodeSandbox</h1> <h2>Start editing to see some magic happen! </h2> <Table dataSource={this.state.dataSource} components={components}> <Table.Column dataIndex="name" title="name" render={(text, record, index) => { if (record.type === 1) { return ( <Input // key={index} value={this.state.tableInput} onChange={(e) => { // this.handleInputChange(e, text, index); this.setState({ tableInput: e.target.value }); }} / >); } if (record.type === 2) { return text; } }} /> </Table> <Input.TextArea value={JSON.stringify(this.state.dataSource, null, 2)} autoSize /> </div> ); }}

Revised renderings:



Github

https://github.com/blueju/BlogCodeSandBox/tree/master/input-onblur-in-antd-table