我有两个文件App.js和Card.js。 App.js正在获取键,值的数组并将其以Cards的形式呈现到屏幕上。在卡片中,我从App中获取道具并将其分配给卡片状态下的变量。
我有一个按钮,调用函数onCardPress(),该函数检查卡的状态是否处于活动状态,如果是,则发送警报,显示我按下的卡(卡类型)。
我注意到,如果我使用this.state.cardType,则为cardType返回的变量为'undefined',并且onCardPress函数不起作用,因为this.state.cardActive也为'undefined'。但是,如果将其更改为this.props.cardType和this.props.cardActive,则会从App.js获取正确传递的输入。
此外,为什么此行为不会影响render函数中的Image标签。我可以同时输入this.state和this.props,并且两次图像均正确显示。
为什么会这样?
App.js
export default class App extends Component {
constructor(props){
super(props);
this.state = {
hand:
[
{card: "heart1", key: 1, cardFace: Images.heart1, active: true},
{card: "heart2", key: 2, cardFace: Images.heart2, active: true},
{card: "heart6", key: 6, cardFace: Images.heart6, active: true},
{card: "heart4", key: 4, cardFace: Images.heart4, active: true},
{card: "heart13", key: 13, cardFace: Images.heart13, active: true}
]
};
}
render() {
return (
<View style={styles.hand}>
{
this.state.hand.map((prop) => {
return(
<Card
cardFace={prop.cardFace}
key={prop.key}
cardType={prop.card}
cardActive={prop.active}
/>
);
})
}
</View>
)
}
}
Card.js
export default class Card extends Component{
constructor(props){
super(props)
this.state = {
cardFace: props.cardFace,
cardType: props.card,
cardActive: props.active
};
this.onCardPress = this.onCardPress.bind(this)
}
onCardPress(){
if(this.state.cardActive==true){
Alert.alert("pushed " + this.props.cardType)
}
}
render(){
return(
<View>
<TouchableOpacity onPress={this.onCardPress} style={styles.card}>
<Image source={this.state.cardFace} style={styles.card}/>
</TouchableOpacity>
</View>
);
}
}
谢谢。
答案 0 :(得分:0)
尝试设置状态时出错:
def powerset(s):
a = ['']
for i,c in enumerate(s):
for k in range(2**i):
a.append(a[k]+c)
return a
当您尝试获取“ cardType”时,您正在尝试获取“ card”参数。
正确的代码应为:
this.state = {
...
cardType: props.card,
...
};