首页 > 解决方案 > React-Native 如何给方法一个变量

问题描述

我正在尝试更改状态中的变量,因此稍后我将其作为属性提供给组件,但我似乎无法更改该变量。

constructor(){
        super();
        this.state = {
            dataSource: [],
            reading: false,
            iName: 'default'
        };
        this.startRead = this.startRead.bind(this);
    }

    startRead = ({item}) => {
        this.setState({
            reading: true,
            iName: {item.name} //it doesn't work over here
        });
    }

    renderItem = ({item}) => {
        this.setName
        return(
            <TouchableOpacity style={{flex: 1, flexDirection: 'row', marginBottom: 5}} onPress={this.startRead}>
                <Text>{item.name}</Text> // this does work
                <Text>{item.desc}</Text>
            </TouchableOpacity>
        );
    }

我通过 FlatList 调用了这个 renderItem 函数

    this.state.reading ?
    <ReadScreen iname={this.state.iName}/>
    :
    <View style={styles.slide}>
        <FlatList
            data={this.state.dataSource}
            renderItem={this.renderItem}
        />
    </View>

它给了我一个“SyntaxError: App.js: Unexpected token, expected ',' (21,24)”的错误

(21,24) 给出了这条线

iName:{item.name}

我究竟做错了什么?

目标是;当我按下 FlatList 的一个项目时TouchableOpacity,它会呈现显示的 ReadScreen,通过属性而不是 FlatList 提供更多给定信息。

如果不清楚或需要更多信息,请询问

感谢您的时间。

标签: react-native

解决方案


替换此行

onPress={this.startRead}

有了这条线

onPress={() => this.startRead({item})}

这是完整的解决方案

renderItem = ({item}) => {
    this.setName
    return(
        <TouchableOpacity style={{flex: 1, flexDirection: 'row', marginBottom: 5}} onPress={() => this.startRead({item})}>
            <Text>{item.name}</Text> // this does work
            <Text>{item.desc}</Text>
        </TouchableOpacity>
    );
}

推荐阅读