我想在列表中创建玩家的数据,我也想让我的按钮可以编辑玩家的号码。 当我添加播放器时,列表显示得很好。当我编辑号码时,列表未显示新结果。是否可以使ObservedObject观察元素的属性?我尝试在我的ObservedObject中添加@State元素,并且它可以正常工作,但我认为这不是正确的方法。 @State和@ObservedObject有什么区别?当我想在func中使用ObservedObject时,它告诉我“无法分配给属性:'self'是不可变的”。非常感谢您的帮助。
renderGridItem = ({ item }) => (
<TouchableOpacity onPress={()=>this.handleClick()}>
....
...
</TouchableOpacity>
)
这是我的ObserableObject
struct TestView: View {
@ObservedObject var team: TeamMembers = TeamMembers()
@ObservedObject var addPlayer: TeamMember = TeamMember()
@State var number: Int = 0
@State var index: Int = 0
@State var name: String = ""
var body: some View {
VStack(alignment: .leading) {
List(team.teamMembersArray){ (member) in
Text(member.userName)
Text("\(member.uniformNumber)")
}
Text("input uniformNumber")
TextField("input uniformNumber", value: $number, formatter: NumberFormatter())
Text("input index need to edit")
TextField("input index need to edit", value: $index, formatter: NumberFormatter())
Text("input player name")
TextField("input player name", text: $name)
Button(action: self.addNewPlayer){
Text("Add new player")
}
Button(action: self.editPlayer){
Text("edit player name")
}
}
}
func addNewPlayer(){
let newplayer: TeamMember = TeamMember()
// self.addPlayer.userName = name
// self.addPlayer.uniformNumber = number
newplayer.userName = name
newplayer.uniformNumber = number
team.teamMembersArray.append(newplayer)
}
func editPlayer(){
print("Array[\(index)]\(team.teamMembersArray[index].userName)")
team.teamMembersArray[index].userName = name
print(name)
print("Array[\(index)]\(team.teamMembersArray[index].userName)")
}
}