【问题标题】:How to pass text into component in React-Native? (Android)如何将文本传递到 React-Native 中的组件? (安卓)
【发布时间】:2020-08-16 23:07:30
【问题描述】:

我正在调用以下函数

const LevelCard = (level) => {
    const currLevel = level;
    console.log(currLevel)
    return (
        <View style={{
            flex: 1,
            width: 400,
            alignItems: 'center', 
            justifyContent: 'center'
        }}>
        <CategoryButton
            title='Text should go here'
            onPress={() => navigation.navigate('')}
        />
        </View>
    );
}

来自另一个组件

function CallFunction() {
    return (
      <SafeAreaView style={styles.categories}>
        <ScrollView horizontal={true} style={styles.scrollView}>
          <View>

            <LevelCard 
                level="This is the text I want to pass"
            />

          </View>
        </ScrollView>
      </SafeAreaView>
    );
}

但我不知道如何实际从“级别”获取文本以显示在 react-native 组件中的任何位置。但是,console.log 语句在它之外可以正常工作。

谢谢

【问题讨论】:

    标签: android reactjs function react-native mobile


    【解决方案1】:

    我建议你看一下 react 中的 props,用一般的方式来解释它,你可以这样想 props:“props 之于组件,而 arguments 之于函数”。现在您正确地将文本传递给您的 LevelCard 组件,但您没有正确检索它,道具作为对象传递,因此您必须从接收组件中解构它:

    const LevelCard = ({ level }) => { // <--- Notice this line
      const currLevel = level;
      console.log(currLevel)
      return (
        <View style={{
            flex: 1,
            width: 400,
            alignItems: 'center', 
            justifyContent: 'center'
        }}>
        <CategoryButton
            title={level} {/* then use it like this*/}
            onPress={() => navigation.navigate('')}
        />
        </View>
      );
    
    }
    

    【讨论】:

    • 谢谢。尽管添加花括号没有任何作用,但您的建议是合理的。传递道具并做 title = {props.level} 让我可以查明正确的数据
    • 哦,等等,我更新了我的答案忘了指出如何使用它
    • 但你是对的,你也可以这样做 props.level 或任何你的道具名称
    猜你喜欢
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    • 2018-01-15
    • 2021-07-18
    • 1970-01-01
    • 2023-02-17
    • 1970-01-01
    • 2019-02-18
    相关资源
    最近更新 更多