React Native - 基于状态

时间:2018-05-19 02:07:09

标签: react-native

以下是我尝试做的一个简单示例。我在导航栏中有headerLeft,但是当用户点击按钮(Take the Challenge)并因此设置状态变量' next&#时,想让它消失(这样用户就不能再回击) 39;为真。这可能吗?如果是的话,有关于如何的任何建议?

export default class Challenge extends React.Component {
static navigationOptions = ({ navigation }) => ({
    title: "5 Day Challenge",
    headerTintColor: "white",
    headerStyle: { backgroundColor: "black" },
    headerTitleStyle: { fontWeight: "bold", fontSize: moderateScale(15) },
    headerLeft: (
         <Button onPress={() => navigation.goBack(null)}>
            {" "}
            <MaterialCommunityIcons
                name="arrow-left"
                size={28}
            />
        </Button>
    )
});

 constructor(props) {
    super(props);
    this.state = {
        next: false,
    };
   }

render() {
    return (
        <View>
            <Button
                onPress={() =>
                    this.setState({ next: true })}
            >
                <Text >
                    TAKE THE CHALLENGE
                </Text>
            </Button>
            </View>
        )}

}

1 个答案:

答案 0 :(得分:1)

您可以使用this.props.navigation.setParams({...});

export default class Challenge extends React.Component {
    static navigationOptions = ({ navigation }) => {
        const { state } = navigation;
        if (state.params !== undefined) {
            return {
                title: "5 Day Challenge",
                headerTintColor: "white",
                headerStyle: { backgroundColor: "black" },
                headerTitleStyle: { fontWeight: "bold", fontSize: moderateScale(15) },
                headerLeft: state.params.showBack ? (
                    <Button onPress={() => navigation.goBack(null)}>
                        {" "}
                        <MaterialCommunityIcons
                            name="arrow-left"
                            size={28}
                        />
                    </Button>
                ) : null
            }
        }
    };


    constructor(props) {
        super(props);
        this.state = {
            next: false,
        };
    }


    componentDidMount() {
        this.props.navigation.setParams({
            showBack: true
        });
    }

    onClick = () => {
        this.setState({ next: true })
        this.props.navigation.setParams({
            showBack: false
        });
    }


    render() {
        return (
            <View>
                <Button
                    onPress={() => this.onClick()} >
                    <Text >
                        TAKE THE CHALLENGE
                </Text>
                </Button>
            </View>
        )
    }
}

PS:我希望它能运作,我没有测试那段代码。

相关问题