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

How to move an Image on click in React Native

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

我一直在尝试做到这一点,如果我点击 TouchableHighlight,我的图像会向下移动几个像素,但我还没有设法让它移动,老实说,我不知道该怎么做从这里开始。

我的 onclick 函数有效,因为它会在每次单击按钮时 return 记录日志。

截至目前我有这个:

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>
}

如果有人能帮我解决这个问题,我将不胜感激。 非常感谢您的参与!

有很多方法可以做到这一点,但也许最简单的方法是使用 states.

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>
  );
  }
}