javascript - 仅在特定屏幕上渲染子组件中的按钮

标签 javascript reactjs react-native react-native-flatlist react-component

我在两个不同的屏幕上使用平面列表。 在EventListScreen上: 这是主屏幕,应显示所有事件。 在第二页 UserProfile.js 上,此页面应仅显示该用户事件。 在两个平面列表中,我都使用存储在单独的类中的纯组件,即平面列表所在的位置

我的问题是,仅当用户位于 Event.js 子组件上时,我才想显示“编辑”按钮 UserProfileScreen.js

我查了很多例子,但找不到任何说明如何做到这一点的例子 像我一样使用一个纯子组件。

任何帮助将不胜感激!谢谢您

EventListScreen.js

  <FlatList
                data={this.state.events}
                // Get the item data by referencing as a new function to it
                renderItem={({item}) =>
                    <Event
                    openEventDetail={() => this.openEventDetail(item)}
                    {...item}
                    />}
            />

UserProfileScreen.js

  <FlatList
                data={this.state.events}
                // Get the item data by referencing as a new function to it
                renderItem={({item}) =>
                    <Event
                        openEventDetail={() => this.openEventDetail(item)}
                        openEditEvent={() => this.openEditEvent(item)}

                        {...item}
                    />}
            />

Event.js

export default class Event extends Component {

render() {

    return (
        <Card>
            <CardSection>
                <Text>{this.props.eventName}</Text>

                 //I want this button to be displayed only if user is viewing
                 //from the UserProfile.js
                <Button onPress={() =>this.props.openEditEvent()}>
                    {this.props.displayButton}
                </Button>

            </CardSection>

            <TouchableOpacity
              onPress={() => this.props.openEventDetail()}
            >
         }

最佳答案

您不需要其他属性。

我们可以假设定义了 openEditEvent 属性后,“编辑”按钮应该可用。

事件中的条件(使用转换为 bool, false 表示未定义):

        <CardSection>
            <Text>{this.props.eventName}</Text>

            {!!this.props.openEditEvent &&
              <Button onPress={() =>this.props.openEditEvent()}>
                {this.props.displayButton}
              </Button>
            }

        </CardSection>

使用 propTypes 将 openEditEvent prop 定义为函数,可选(非必需)。

关于javascript - 仅在特定屏幕上渲染子组件中的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53176138/

相关文章:

javascript - App.js 中的组件未以 React-Native 方式呈现。请纠正我。

react-native - React 0.18 导致模块错误

javascript - 如何从 android native 代码传递 props 以响应 native

javascript - 添加复选框时出错

javascript - 在 JavaScript 中返回被破坏的参数

Javascript 发货到达日期预测器

javascript - 将 useState() 与事件监听器一起使用时遇到问题。看不到更新的状态

javascript - 使用 react-testing-library 的故事截图

javascript - 如何计算用户在 React Native 中花费的特定屏幕上的时间

javascript - 在jsf中使用json将数据从bean发送到javascript