TextArea、Input与useEffect更改数组与对象里的值
TextArea与Input.jsx
import React, { Component, useState, useEffect } from 'react'
import { Modal, Input } from 'antd'
const { TextArea } = Input;
export default class CompanyAuto extends Component {
constructor(props) {
super(props)
this.state = {
list: [{
detail_text: 'xxx1'
},{
detail_text: 'xxx2'
}],
obj: {
age: "18"
}
}
}
confirmText = (val, idx) => {
const { list } = this.state
/**
* 更改数组里的值
*/
const newPersons = list.concat([]); //复制数组--浅拷贝
newPersons[idx]["detail_text"] = val
this.setState({
...this.state,
list: newPersons
}, () => {
console.log('this.state',this.state)
})
return
/**
* 更改数组与对象里的值
*/
const listData = [...list]; //复制数组--浅拷贝
const nObj = Object.assign({}, this.state.obj, { age: val });
this.setState({
list: listData.map((item, index) => index === idx ? {
...item,
detail_text: val //更改的值
} : item),
obj: nObj
}, () => {
console.log('this.state',this.state)
})
}
render() {
const { list } = this.state
return (
<div>
{list.map((ele, idx) => (
<TextAreaBox detail_text={ele.detail_text} confirmText={(val) => this.confirmText(val, idx)}/>
))}
</div>
)
}
}
const TextAreaBox = (props) => {
const { detail_text } = props
const [detailText, setDetailText] = useState(detail_text);
// useEffect 在 React 更新 DOM 之后运行一些额外的代码。比如发送实时更新的网络请求(输入搜索)
useEffect(() => {
console.log('detailText', detailText)
})
// useEffect(() => {}, [detailText]); // 仅在 detailText 更改时更新
const textAreaBlur = (e) => {
Modal.confirm({
content: '确定要修改吗?',
type: 'warning',
onOk: () => {
props.confirmText(detailText)
},
onCancel: () => {
setDetailText(detail_text)
}
})
}
const textAreaChange = ({ target: { value } }) => {
setDetailText(value)
}
return (
<div>
<TextArea placeholder="列表里更改input数据" autoSize={{ minRows: 3, maxRows: 5 }} value={detailText}
onChange={textAreaChange} onBlur={textAreaBlur}/>
</div>
)
}

浙公网安备 33010602011771号