首页 > 解决方案 > React Native 将组件传递给组件

问题描述

我是本机反应的新手,不确定如何在组件之间传递组件。

我创建了一组能够生成表格的函数。我试图通过允许entryData成为组件以及字符串或数字类型来使表格更通用。

如果useTextWrapper为真且类型entryData为数字或字符串,则表格会将数据放入文本组件中。否则,我假设它entryData必须是一个组件,然后我只想entryData在视图组件中解包。这是我到目前为止所尝试的,我得到一个“必须在文本组件中呈现文本字符串”。有没有办法做我想做的事?

function EntryDataWrapper(props) {
    return <View> {props.children} </View>;
}
function RowEntry(props) {
    let {entryStyle, entryTextStyle, entryData, useTextWrapper} = props;
    const theType = typeof entryData;
    return (
        <View style={entryStyle}>
            {useTextWrapper && (theType == 'nuber' || theType == 'string') ? (
                <Text style={entryTextStyle}>{entryData}</Text>
            ) : (
                <EntryDataWrapper> {entryData} </EntryDataWrapper>
            )}
        </View>
    );
}

标签: javascriptreact-nativecomponents

解决方案


错误消息已经说明了问题。 Text strings must be rendered within text components. EntryDataWrapper 组件没有这样做。

因此,您应该将 Text 组件添加到其中。请按照下面的代码。

     function EntryDataWrapper(props) {
        return <View> <Text>{props.children}</Text> </View>;
     }
    function RowEntry(props) {
        let {entryStyle, entryTextStyle, entryData, useTextWrapper} = props;
        const theType = typeof entryData;
        return (
            <View style={entryStyle}>
                {useTextWrapper && (theType == 'nuber' || theType == 'string') ? (
                    <Text style={entryTextStyle}>{entryData}</Text>
                ) : (
                    <EntryDataWrapper> {entryData} </EntryDataWrapper>
                )}
            </View>
        );
    }

欢呼!


推荐阅读