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

jas*_*per 3 javascript dom dom-manipulation react-native

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

我一直在努力做到,如果我单击TouchableHighlight,我的图像会向下移动几个px,但是我还没有设法使其移动,而且老实说,我不知道该怎么做。

我的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>
}
Run Code Online (Sandbox Code Playgroud)

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

Tru*_*eel 5

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

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>
  );
  }
}
Run Code Online (Sandbox Code Playgroud)