【问题标题】:React Native onPress fuction is not workingReact Native onPress 功能不起作用
【发布时间】:2019-05-26 02:44:57
【问题描述】:

我正在做一些显示图书信息的项目。我已成功从服务器获取数据,并希望使用 onPress 功能使模态弹出并消失。但它不工作。模态显示,但不会消失。

我尝试将 this.togglePopoff.bind(this) 放入构造函数中,但没有成功。 我还在函数 'togglePopoff' 中使用 console.log("I'm press button") 检查了日志,但日志也没有显示。

这是我的构造函数

constructor(props) {
    super(props);
    this.state = {
        currentDate: new Date(),
        markedDate: moment(new Date()).format(),
        isPopVisible: false,
        apiData: [],
        activeSwitch: 1,
    }
    this.ISBN = null;
    this.book_name = null;
    this.img_src = null;
    this.author = null;
    this.publisher = null;
    this.public_date = null;
    this.more_url = null;
    this.read_rate = null;
    this.read_date = null;
    this.category = null;
    this.best = null;
    this.togglePopoff = this.togglePopoff.bind(this);
}

这是我消失模式的功能。

togglePopoff = () => {
    this.setState({ isPopVisible: false });
}
saveBook = () => {
    this.setState({ isPopVisible: false });

}

这是我的 searchBook 函数。

searchBook = () => {
    this.setState({ isPopVisible: true });
    // popup - onoff
    if(this.ISBN == null){
        this.setState({ isPopVisible: false});
        alert("please input ISBN code");
        //return 0;
    }
    else {

    fetch('http://220.149.242.12:10001/search/book/' + (this.ISBN), {
        method: 'GET'
    }).then((responseData) => {
        return responseData.json();
    }).then((jsonData) => {
        console.log(jsonData);
        this.setState({ apiData: jsonData })
        console.log(this.state.apiData)
    }).done();
    this.ISBN = null;
    this.book_name = null;
    this.img_src = null;
    this.author = null;
    this.publisher = null;
    this.public_date = null;
    this.more_url = null;
    this.read_rate = null;
    this.read_date = null;
    this.category = null;
    this.best = null;
    };
}

这就是 onPress 的用武之地。

render() {
    const data = this.state.apiData;
    const today = this.state.currentDate;
    var dataDisplay = null;
    if (data && data.items) {
        dataDisplay = data.items.map(function (item) {
            //var image = "'" + item.image + "'";
            var image = item.image;
            console.log(image);
            return (
                <View key={item.user_name} style={styles.popfirst}>
                    <View style={styles.popsecond}>
                        <View style={styles.popthird}>
                            <View style={{ paddingTop: 30, }}>
                                <Text style={{ color: '#52C8B2', fontSize: 20, }}>book information</Text>
                            </View>
                            <View style={{ paddingTop: 20, }}>
                                <Image style={{ height: 250, width: 150,  resizeMode: 'contain', }}
                                    source={{ uri: image }}>
                                </Image>
                            </View>
                            <View style={{ paddingTop: 10, }}>
                                <Text style={{ fontSize: 18, }}>{item.title}</Text>
                            </View>
                            <View style={{ paddingTop: 10, }}>
                                <Text style={{ color: '#D7D7D7' }}>{item.author} | {item.publisher} | {item.pubdate}</Text>
                            </View>
                            <View style={styles.popbtn}>
                                <View style={{ width: 10, }}></View>
                                <View style={styles.popbtnleft}>
                                    <SwitchButton
                                        onValueChange={(val) => this.activeSwitch(val)} 
                                        text1='reading'
                                        text2='done'
                                        switchWidth={120}
                                        switchHeight={30}
                                        switchdirection='ltr'
                                        switchBorderRadius={0}
                                        switchSpeedChange={500}
                                        switchBorderColor='#52C8B2'
                                        switchBackgroundColor='#F2F2F2'
                                        btnBorderColor='#52C8B2'
                                        btnBackgroundColor='#52C8B2'
                                        fontcolor='#333'
                                        activeFontColor='#FFF'
                                    />
                                </View>
                            </View>
                            <View style={styles.popbtnbig}>
                                <TouchableOpacity style={styles.bigbtn} onPress={this.togglePopoff}><Text style={{ fontSize: 16, color: '#FFF' }}>cancle</Text></TouchableOpacity>
                                <TouchableOpacity style={styles.bigbtn} onPress={this.saveBook}><Text style={{ fontSize: 16, color: '#FFF' }}>save</Text></TouchableOpacity>
                            </View>
                        </View>
                    </View>
                </View>
            )
        });
    };
    return (
        <View style={cstyle.greycontainer}>
            <View style={styles.firstbox}>
                <Text style={{ color: '#FFF', fontSize: 20 }}>input ISBN code</Text>
            </View>
            <View style={styles.secondbox}>
                <TextInput style={styles.input}
                    placeholder="Enter ISBN"
                    onChangeText={(text) => { this.ISBN = text }}
                    value={this.ISBN}
                />
                <TouchableOpacity style={styles.searchbtn} onPress={this.searchBook}>
                    <IonIcon name="ios-search" size={30} color='#FFF' />
                </TouchableOpacity>
            </View>
            <View style={styles.firstbox}>
                <TouchableOpacity style={styles.greenbtn}>
                    <Text style={{ color: '#FFF', fontSize: 20 }}>cancle</Text>
                </TouchableOpacity>
            </View>
            <Modal isVisible={this.state.isPopVisible}>
                {dataDisplay}
            </Modal>
        </View>
    );

}
}

如何关闭模式?

【问题讨论】:

    标签: javascript react-native react-native-android


    【解决方案1】:

    this.togglePopoff = this.togglePopoff.bind(this);

    由于你已经在使用箭头函数,所以你不需要绑定你的函数。 bind 方法已经存在于箭头函数中。

    togglePopoff = () => {
        this.setState({ isPopVisible: false });
    }
    

    这是正确的,只需从构造函数中删除绑定方法即可。

    【讨论】:

    • 我删除了它但仍然无法正常工作......也许是因为模态标签中的 isVisible ?
    【解决方案2】:

    编辑 尝试像这样在constructor 中绑定你的所有函数:

    constructor(props) {
        super(props);
        this.state = {
            currentDate: new Date(),
            markedDate: moment(new Date()).format(),
            isPopVisible: false,
            apiData: [],
            activeSwitch: 1,
        }
        this.ISBN = null;
        this.book_name = null;
        this.img_src = null;
        this.author = null;
        this.publisher = null;
        this.public_date = null;
        this.more_url = null;
        this.read_rate = null;
        this.read_date = null;
        this.category = null;
        this.best = null;
        this.togglePopoff = this.togglePopoff.bind(this);
        this.saveBook = this.saveBook.bind(this);
    }
    

    像这样创建你的函数:

    togglePopoff(){
        this.setState({ isPopVisible: false });
    }
    saveBook(){
        this.setState({ isPopVisible: false });
    }
    

    然后这样称呼他们:

     <TouchableOpacity style={styles.bigbtn} onPress={() => this.togglePopoff()}><Text style={{ fontSize: 16, color: '#FFF' }}>cancle</Text></TouchableOpacity>
     <TouchableOpacity style={styles.bigbtn} onPress={() => this.saveBook()}><Text style={{ fontSize: 16, color: '#FFF' }}>save</Text></TouchableOpacity>
    

    【讨论】:

    • it seams onPress 正在工作,但出现错误,“this2.togglePopoff 不是函数。(在 '_this2.togglePopoff().','_this2.togglePopoff' 未定义)”
    • 所以现在它想做点什么却报错了?我理解对了吗?
    • 嗯...是的,我认为 onPress 开始调用该函数。但是函数出错了。我将 console.log("working function") 放在 togglePopoff 函数中,但日志没有显示并给出错误。
    • 感谢您的友好回复,但它也无法正常工作......仍然出现同样的错误:(
    • 我解决了!!!!我将“dataDisplay = data.items.map(function (item)”更改为“dataDisplay = data.items.map(item=>{}”并且它正在工作!非常感谢您的回复!:D美好的一天!