如何使用onChangeMyData方法,下面的方法未设置状态。 如何通过传递密钥为用户对象分配状态。 如果是嵌套对象,请先感谢
<TextInput
value={user ? user.FirstName : ''}
onChangeText={text =>
this.onChangeMyData('FirstName', text)}
<TextInput
value={user ? user.LastName : ''}
onChangeText={text =>
this.onChangeMyData('LastName', text)}/>
<TextInput
value={toGoData ? toGoData.Note : ''}
onChangeText={text =>
this.onChangeMyData('Note', text)} />
private onChangeMyData(key: keyof IData, value: any) {
this.setState(prevState => ({
myData: { ...prevState.myData, [key]: value },
}));
}
interface IData{
user:Person,
Note:string
}
interface Person {
FirstName:string,
LastName:string
}
答案 0 :(得分:0)
您可以查看此示例,默认值处于状态,并且onChange函数将状态更改为触发状态的字段的名称。
import React from 'react';
class UseLegalyonChange extends React.Component{
constructor(props){
super(props);
this.state={
lastname:"",
phone:"",
address:"",
firstname:""
}
this.handleonChange=this.handleonChange.bind(this);
}
handleonChange(e){
this.setState({[e.target.name]:e.target.value});
}
render(){
return(
<div>
<input type="text" value={this.state.firstname} name="firstname" onChange={(e)=>this.handleonChange(e)}/>
<input type="text" value={this.state.lastname} name="lastname" onChange={(e)=>this.handleonChange(e)}/>
<input type="text" value={this.state.address} name="address" onChange={(e)=>this.handleonChange(e)}/>
<input type="text" value={this.state.phone} name="phone" onChange={(e)=>this.handleonChange(e)}/>
</div>
)
}
}
export default UseLegalyonChange