React Native和JSON文件解析

问题描述 投票:0回答:1

我有一些这样的卡类:

export default class TestCard1 extends React.Component {
     render () {
     return (
   <CardView style={styles.card}>
      <Text style = {styles.word}>
      "word"
      </Text>
  </CardView>
);}} 

这会创建一个闪卡。我在JSON文件中有一个“单词”列表,我想为每个单词创建一个flashcard。我可以访问一个单词

{rowData.word}

我不确定如何“遍历”json文件中的每个单词并从中创建一张卡片。有人可以帮忙吗?谢谢。

android ios json reactjs mobile
1个回答
1
投票

导入您的json文件,然后使用json.stringify在父组件中设置setState。然后使用.map函数循环遍历每个单词并通过props将其传递到您的Card组件中。

import words from './words.json'
import Card from './TestCard1'

class parentclass extends React.Component{
  state={
    data: []
  }
  componentDidMount = () => {
    const data = json.stringify(words)
    this.setState({ data })
  }

  render(){
    const words = () => {
      this.state.data.map(word => <Card word={word} />)
    }
    return(
      <View>
        {words()}
      </View>
    )
  }
}

您的Word组件可以重新构建为“纯”组件,并且只接收来自上面构造的父组件的数据。您可以向View标记添加样式,使其看起来更像卡片。

const Card = ({ word }) => (
   <View>
      <Text>
        {word}
      </Text>
  </View>
)
export default Card
© www.soinside.com 2019 - 2024. All rights reserved.