【问题标题】:React Native, Unexpected Keyword "This"React Native,意外的关键字“This”
【发布时间】:2020-11-06 16:41:29
【问题描述】:

为什么我有一个红色的错误标记这个关键字后面的点?它说(意外的关键字“这个”)

    render() {
    return (
        <TouchableOpacity onPress={() => this.selectionOnPress({this.props.detail.country})}>
            <Text style={[styles.btnSV, {
                backgroundColor:
                    this.state.selectedButton === {this.props.detail.country} ? "red" : "grey"
            }]}>
                <Text style={styles.btnSV}>{this.props.detail.country}</Text>
            </Text>
        </TouchableOpacity>

    );
}}

Error image

【问题讨论】:

  • 当你将鼠标悬停在它上面时它会说什么?
  • @Nathan 它说(意外的关键字“这个”)

标签: javascript html reactjs react-native jsx


【解决方案1】:

试试这个

render() {
    return (
        <TouchableOpacity onPress={() => this.selectionOnPress(this.props.detail.country)}>
            <Text style={[styles.btnSV, {
                backgroundColor:
                    this.state.selectedButton === this.props.detail.country ? "red" : "grey"
            }]}>
                <Text style={styles.btnSV}>{this.props.detail.country}</Text>
            </Text>
        </TouchableOpacity>

    );
}}

我基本上从this.props.detail.country 的第一个和第二个实例中删除了周围的大括号 在 JS 中,这些大括号是对象表示法,并且缺少属性名称。 第三个实例是 JSX 模板变量。

【讨论】:

  • 它不像以前那样在红色和灰色之间切换。
  • 那么我的猜测是 selectionOnPress() 更新 state.selectedButton?如果 state.selectedButton 的初始值为 falsy,第一次点击会将其设置为 props.detail.country 并将按钮背景更改为红色。现在如果你再次点击它会发生什么?还有另一个按钮可以将 state.selectedButton 设置为不同的值吗?
  • constructor() { super(); this.state = { selectedButton: null }; this.selectionOnPress = this.selectionOnPress.bind(this); } selectionOnPress(userType) { this.setState({ selectedButton: userType }); }
  • 然后,在selectionOnPress() 中,执行以下操作:this.setState(preState =&gt; prevState.selectedButton === userType ? null : userType) 这将在点击同一按钮时在 null 和 value 之间切换,并且应该在红色和灰色按钮之间切换。
  • 即使我点击了两次,它也只给我灰色。 stackoverflow.com/a/48444567/13854515这个解决方案不起作用。
猜你喜欢
  • 2018-05-07
  • 2020-05-04
  • 2019-02-01
  • 1970-01-01
  • 2016-02-08
  • 2019-07-18
  • 1970-01-01
  • 2021-10-12
  • 2015-06-01
相关资源
最近更新 更多