如何在React Native中点击移动图片

5

我最近一直在学习React Native,但是还没有找到操作DOM的方法。

我试图通过点击TouchableHighlight来使我的图片向下移动几个像素,但是我尚未成功移动它,而且实际上我不知道该从哪里入手。

我的onclick函数有效,因为每次点击按钮时都会记录日志。

目前为止,我有以下代码:

export default class MainBody extends Component {

  onclick = () => {
    console.log('On click works')
  };

  render() {

    return (

      <ScrollView showsHorizontalScrollIndicator={false} style={Style.horList} horizontal={true}>

        <View >

          {/*i need to move this Image down!*/}
          <Image source={require("./img/example.png")}/>
          <View>
            <Text style={Style.peopleInvited}>This is text</Text>
          </View>

          {/*When clicked on this touchable highlight!*/}
          <TouchableHighlight onPress={this.onclick}}>
            <Image source={require('./img/moveImg.png')}/>
          </TouchableHighlight>
        </View>

      </ScrollView>
}

如果有人能帮我解决这个问题,那将不胜感激。非常感谢你的时间!
1个回答

9

有很多方法可以做到这一点,但可能最简单的方法是使用 状态

class MainBody extends Component {
    constructor(props) {
        super(props);
        this.state = {
            top: 0 // Initial value
        };
    }
  onclick = () => {
    console.log('On click works')
    this.setState( { top: this.state.top + 5 }) // 5 is value of change.
};


  render() {

    return (

      <ScrollView showsHorizontalScrollIndicator={false} horizontal={true}>

        <View >

          {/*i need to move this Image down!*/}
          <Image style={{top: this.state.top}}source={require("./img/example.png")}/>
          <View>
            <Text>This is text</Text>
          </View>

          {/*When clicked on this touchable highlight!*/}
          <TouchableHighlight onPress={this.onclick}>
            <Image source={require("./img/moveImg.png")}/>
          </TouchableHighlight>
        </View>

      </ScrollView>
  );
  }
}

那看起来确实是一种非常简单和干净的方法,非常感谢! - jasper

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接