【问题标题】:React Native Touchable on press down event在按下事件时反应 Native Touchable
【发布时间】:2017-01-04 17:54:02
【问题描述】:

我正在尝试创建一个类似于 TouchableHighlight 的组件,但我不想突出显示背景,而是要突出显示文本。我需要挂钩在用户实际按下时触发的 onPress 事件。

我尝试过使用 TouchableWithoutFeedback 和 onPressIn,但它似乎没有触发。这是我一直在测试的代码。

class TouchableTextHighlight extends React.Component {

constructor (props) {
    super(props)

    this.state = {
        isHighlighted: false
    }
}

highlight () {
    console.log('pressed')
    this.setState({
        isHighlighted: true
    })
}

render () {
    let textColor = this.state.isHighlighted ? '#F44336' : null

    return (
        <TouchableWithoutFeedback {...this.props} onPressIn={() => {this.highlight}} onPress={this.props.onPress}>
            <View {...this.props}>
                <Text
                style={[this.props.textStyle, {color: textColor}]}
                >{this.props.text}</Text>
            </View>
        </TouchableWithoutFeedback>
    )
}

}

【问题讨论】:

    标签: react-native


    【解决方案1】:

    您需要调用该方法。变化:

    onPressIn={() => {this.highlight}}
    

    onPressIn={() => {this.highlight()}}
    

    【讨论】:

      【解决方案2】:

      你的代码非常好,但你错过了一件非常重要的事情——Binding functions。您的highlight 函数未绑定到上下文。绑定函数的方式有很多种,这里只讲一种比较高效的方式。

      highlight () {
      console.log('pressed')
      this.setState({
          isHighlighted: true
      })
      }
      

      像这样重写上面的函数

      highlight = () => {
      console.log('pressed')
      this.setState({
          isHighlighted: true
      })
      }
      

      如果您想在react check out here 中阅读有关绑定的更多信息

      【讨论】:

        猜你喜欢
        • 2019-06-19
        • 2023-03-10
        • 1970-01-01
        • 1970-01-01
        • 2021-01-12
        • 1970-01-01
        • 1970-01-01
        • 2016-12-02
        • 1970-01-01
        相关资源
        最近更新 更多