我是 React Native 的新手,所以我知道我还有很多东西需要学习。
我在这里创建一个自定义类组件:
import React, { Component, useState } from 'react';
import {View,Text,StyleSheet,TextInput, Button} from 'react-native';
class Square extends React.Component{
constructor(pos,text,won,save){
this.state = {
pos : 0,
text : 'EDIT',
won : false,
save : false,
};
}
setPos = (pos) =>{
this.setState(pos)
}
getPos = () => {
return (this.pos);
}
setText=(text)=>{
this.setState(text)
}
getText=()=>{
return (this.text);
}
setWon=(won)=>{
this.setState(won)
}
getWon=()=>{
return (this.won);
}
setSave=(save)=>{
this.setState(save)
}
getSave=()=>{
return (this.save);
}
};
export default Square;
然后我想在不同的组件中创建这些对象的数组,并显示每个对象的一条信息。
import {View, Text, StyleSheet, Button, Alert} from 'react-native';
import Square from '../components/Square';
const NewGameScreen = () => {
let arrSquare = [];
for (let i = 0; i < 25; i++){
arrSquare.push({
THIS IS WHERE I'M HAVING TROUBLE
});
}
console.log(arrSquare[0].getPos)
return(
<View style = {styles.screen}>
<View style = {styles.row}>
<Text>{arrSquare[0].getPos}</Text>
</View>
</View>
)
};
但是从上面的代码我确信我显然遗漏了一些东西。我本来希望使用类似 Square[i].setPos(i);
的东西,但这会引发错误。控制台日志还给出“未定义”,这让我觉得我还没有声明某些东西或者没有正确声明它。提前致谢。
最佳答案
我的方法是使用一个简单的 json 对象数组,如下所示:
let squareArr = [{
id: 0,
pos : 0,
text : 'EDIT',
won : false,
save : false,
},
{
id: 1,
pos : 0,
text : 'EDIT',
won : false,
save : false,
},
{
id: 2,
pos : 0,
text : 'EDIT',
won : false,
save : false,
}
]
然后您就可以进行读取和编辑。
显示位置:
在你的渲染方法中你可以这样做:
<View style = {styles.screen}>
<View style = {styles.row}>
squareArr.map((square) => <Text>{square.pos}</Text>)
</View>
</View>
编辑位置:
如果您想更改 JSON 中的值,则只需使用对象索引来指示您要更改哪个对象。例如想要更改第二个对象的 pos ,那么我会这样做:
squareArr[1].pos = 3
我不太确定整个项目是什么,以便为您提供最好的解决方案,但我希望这会有所帮助..
如有任何疑问,请随时询问
关于javascript - 如何在 React Native 中从单独的组件创建对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62942317/